How to fit text in a circle in UILabel

前端 未结 4 1915
情歌与酒
情歌与酒 2020-12-28 20:51

I\'d like to flow the text in UILabel into a circle (instead of rect). I did some experiments with NSLayoutManager, NSTextContainer an

4条回答
  •  无人及你
    2020-12-28 21:02

    You can't do this in a UILabel because it doesn't give you access to the TextKit stack. What I do is to build my own TextKit stack and subclass NSTextContainer:

    -(CGRect)lineFragmentRectForProposedRect:(CGRect)proposedRect atIndex:(NSUInteger)characterIndex writingDirection:(NSWritingDirection)baseWritingDirection remainingRect:(CGRect *)remainingRect {
        CGRect result = [super lineFragmentRectForProposedRect:proposedRect atIndex:characterIndex writingDirection:baseWritingDirection remainingRect:remainingRect];
        CGRect r = CGRectMake(0,0,self.size.width,self.size.height);
        UIBezierPath* circle = [UIBezierPath bezierPathWithOvalInRect:r];
        CGPoint p = result.origin;
        while (![circle containsPoint:p]) {
            p.x += .1;
            result.origin = p;
        }
        CGFloat w = result.size.width;
        p = result.origin;
        p.x += w;
        while (![circle containsPoint:p]) {
            w -= .1;
            result.size.width = w;
            p = result.origin;
            p.x += w;
        }
        return result;
    }
    

    Crude but effective. Looks like this:

    enter image description here

提交回复
热议问题