Giving Framesetter the correct line spacing adjustment

后端 未结 2 1452
隐瞒了意图╮
隐瞒了意图╮ 2021-01-03 11:27

Several posts have noted difficulties with getting an exact height out of CTFramesetterSuggestFrameSizeWithConstraints, and here, (framesetter post), @Chris DeSalvo gives wh

2条回答
  •  无人及你
    2021-01-03 11:58

    I too ran into this and here is the code that worked in a real project:

    // When you create an attributed string the default paragraph style has a leading 
    // of 0.0. Create a paragraph style that will set the line adjustment equal to
    // the leading value of the font. This logic will ensure that the measured
    // height for a given paragraph of attributed text will be accurate wrt the font.
    
    - (void) applyParagraphAttributes:(CFMutableAttributedStringRef)mAttributedString
    {
      CGFloat leading = CTFontGetLeading(self.plainTextFont);
    
      CTParagraphStyleSetting paragraphSettings[1] = {
        kCTParagraphStyleSpecifierLineSpacingAdjustment, sizeof (CGFloat), &leading
      };
    
      CTParagraphStyleRef  paragraphStyle = CTParagraphStyleCreate(paragraphSettings, 1);
    
      CFRange textRange = CFRangeMake(0, [self length]);
    
      CFStringRef keys[] = { kCTParagraphStyleAttributeName };
      CFTypeRef values[] = { paragraphStyle };
    
      CFDictionaryRef attrValues = CFDictionaryCreate(kCFAllocatorDefault,
                                                      (const void**)&keys,
                                                      (const void**)&values,
                                                      sizeof(keys) / sizeof(keys[0]),
                                                      &kCFTypeDictionaryKeyCallBacks,
                                                      &kCFTypeDictionaryValueCallBacks);
    
      BOOL clearOtherAttributes = FALSE;
      CFAttributedStringSetAttributes(mAttributedString, textRange, attrValues, (Boolean)clearOtherAttributes);
      CFRelease(attrValues);
    
      CFRelease(paragraphStyle);
    
      self.stringRange = textRange;
    
      return;
    }
    

提交回复
热议问题