UILabel default kerning different from CATextLayer

后端 未结 3 2117
天命终不由人
天命终不由人 2021-02-08 00:19

I have a UILabel with the string \'LA\'. I also have a CATextLayer with the same characters in an NSAttributedString assigned to its

3条回答
  •  天涯浪人
    2021-02-08 00:39

    you should add attribute to your NSMutableAttributedString.

    For the kerning:

        CGFloat characterspacing = 10.0f;
        CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&characterspacing);
        [string addAttribute:(id)kCTKernAttributeName value:(id)num range:NSMakeRange(0 , [string length])];
        CFRelease(num);
    

    If you also need the line spacing, or set LineBreadMode:

        CTLineBreakMode linebreak = kCTLineBreakByCharWrapping;
        CTParagraphStyleSetting linebreakStyle;
        linebreakStyle.spec = kCTParagraphStyleSpecifierLineBreakMode;
        linebreakStyle.valueSize = sizeof(linebreak);
        linebreakStyle.value = &linebreak;
    
        CTParagraphStyleSetting lineSpaceStyle;
        CGFloat linespacing = self.linesSpacing;
        lineSpaceStyle.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;
        lineSpaceStyle.valueSize = sizeof(linespacing);
        lineSpaceStyle.value =&linespacing;
        CTParagraphStyleSetting settings[ ] ={linebreakStyle,lineSpaceStyle};
        CTParagraphStyleRef style = CTParagraphStyleCreate(settings ,2);
        [string addAttribute:(id)kCTParagraphStyleAttributeName value:(id)style range:NSMakeRange(0 , [string length])];
        CFRelease(style);
    

    At the end, may you need calculate the number of line(linenum) about your kerning,line spacing and LineBreakMode:

    CTFramesetterRef myframesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)string);
    CGMutablePathRef leftColumnPath = CGPathCreateMutable();
    CGPathAddRect(leftColumnPath, NULL ,CGRectMake(0 , 0 , Lable.frame.size.width, MAXFLOAT));
    CTFrameRef leftFrame = CTFramesetterCreateFrame(myframesetter,CFRangeMake(0, 0), leftColumnPath , NULL);
    CFArrayRef lines = CTFrameGetLines(leftFrame);
    linenum = (int)CFArrayGetCount(lines);
    CFRelease(myframesetter);
    CFRelease(leftFrame);
    CGPathRelease(leftColumnPath);
    

提交回复
热议问题