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

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

问题描述

我想将 UILabel 中的文本排成一个圆圈(而不是矩形).我用 NSLayoutManagerNSTextContainerNSTextStorage 做了一些实验,但它似乎不起作用.下面的示例应该将文本流入一个较小的 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;

艾德斯?

推荐答案

这似乎是一个非常简单的解决方案.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天全站免登陆