如何在UILabel中将文本放入圆圈中 [英] How to fit text in a circle in UILabel

查看:119
本文介绍了如何在UILabel中将文本放入圆圈中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 UILabel 中的文本转换为圆圈(而不是rect)。
我用 NSLayoutManager NSTextContainer NSTextStorage 但它似乎不起作用。
以下示例应该将文本流入40x40的较小矩形(标签为120x120),但似乎没有任何影响。

I'd like to flow the text in UILabel into a circle (instead of rect). I did some experiments with NSLayoutManager, NSTextContainer and NSTextStorage but it does not seem to work. The example below is supposed to flow the text into a smaller rect of 40x40 (label is 120x120) but does not seem to have any effect.

UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:12];
NSTextStorage *ts = [[NSTextStorage alloc] initWithString:multiline.title attributes:@{NSFontAttributeName:font}];
NSLayoutManager *lm = [[NSLayoutManager alloc] init];
NSTextContainer *tc = [[NSTextContainer alloc] initWithSize:CGSizeMake(40, 40)];
[lm addTextContainer:tc];
[ts addLayoutManager:lm];
self.label.attributedText = ts;

Ides?

推荐答案

这似乎是一个非常简单的解决方案。 NSTextContainer 有一个 exclusionPaths 属性。你可以做的是创建两个Bezier路径,定义应该排除的区域。

This appeared to be a very simple solution. NSTextContainer has an exclusionPaths property. What you can do is to create two Bezier paths that will define areas that should be excluded.

所以我这样做了,这是我的方法:

So I did that and here is my method:

- (void)setCircularExclusionPathWithCenter:(CGPoint)center radius:(CGFloat)radius textView:(UITextView *)textView
{
    UIBezierPath *topHalf = [UIBezierPath bezierPath];
    [topHalf moveToPoint:CGPointMake(center.x - radius, center.y + radius)];
    [topHalf addLineToPoint:CGPointMake(center.x - radius, center.y)];
    [topHalf addArcWithCenter:center radius:radius startAngle:M_PI endAngle:0.0f clockwise:NO];
    [topHalf addLineToPoint:CGPointMake(center.x + radius, center.y + radius)];
    [topHalf closePath];

    UIBezierPath *bottomHalf = [UIBezierPath bezierPath];
    [bottomHalf moveToPoint:CGPointMake(center.x - radius, center.y - radius)];
    [bottomHalf addLineToPoint:CGPointMake(center.x - radius, center.y)];
    [bottomHalf addArcWithCenter:center radius:radius startAngle:M_PI endAngle:0 clockwise:YES];
    [bottomHalf addLineToPoint:CGPointMake(center.x + radius, center.y - radius)];
    [bottomHalf closePath];

    textView.textContainer.exclusionPaths = @[bottomHalf, topHalf];
}

用法示例:

[self setCircularExclusionPathWithCenter:CGPointMake(160.0f, 200.0f)
                                  radius:100.0f
                                textView:_textView];

我的实验结果:

当然,你会必须使用UITextView而不是UILabel,但我希望它有所帮助:)

Of course you will have to use a UITextView instead of UILabel but I hope it helps :)

这篇关于如何在UILabel中将文本放入圆圈中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆