UILabel斜体字体剪辑

Ama*_*ulo 6 objective-c uilabel uifont ios

我正在尝试解决这个问题,因为在我正在处理的应用程序中我有很多字体,所以当用户更改字体时,动态计算标签的大小.

我有的问题是,如果字体是斜体,UILabel会被剪裁在最后:如下图所示:

UILabel剪辑示例

这是我到目前为止所尝试的:

  • 借助CoreText和.计算宽度 CGSize CTFramesetterSuggestFrameSizeWithConstraints ( CTFramesetterRef framesetter, CFRange stringRange, CFDictionaryRef frameAttributes, CGSize constraints, CFRange *fitRange );
  • 借助NSAttributedString和.计算宽度 - (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context
  • 借助NSString和.计算宽度 - (CGSize)sizeWithAttributes:(NSDictionary<NSString *,id> *)attrs
  • 使用temp UITextView和sizeThatFits´ andfitToSize`

由于应用程序中有很多字体,我需要动态设置标签的宽度,因此UILabel的子类化和添加更多的点drawFrameInRect是不起作用的.

这是Github上的示例代码.

任何帮助/建议表示赞赏.

Ami*_*wad 0

即使我没有时间测试它,我也很确定问题在于标签尺寸是根据预付款计算的。前进是指从一个角色的基点到下一个角色的移动量。通常,对于斜体字体,前进可以小于界限。因此,添加进步将减少布局的结束。

\n\n

即巴斯克维尔斜体H

\n\n
(lldb) p bounds[0].size\n(CGSize) $6 = (width=33.53515625, height=26.484375)\n(lldb) p advances[0]\n(CGSize) $7 = (width=30, height=0)\n
Run Code Online (Sandbox Code Playgroud)\n\n

所以我认为,如果文本以理想的方式布局(无压缩等),则必须添加最后一个字符的提前和边界框之间的差异。

\n\n

要获取这两个值,您必须调用一些 CT 函数:

\n\n
// What you probably have\nCTFontRef font = \xe2\x80\xa6;\nCFStringRef string = \xe2\x80\xa6;\nCFAAttributedStringRef attrString = CFAttributedStringCreate(kCFAllocatorDefault, string, attributes);\n\n// Get the character and glyph\nCFIndex count = CFStringGetLength(string); // The length of the string\nUniChar character;\nCFStringGetCharacters( string, CFMakeRange( count-1, 1), &character );\nCGGlyph glyph;\nCTStringGetGlyphsForCharacters( font, &character, &glyph,1  );\n\n// Get the advance\nCGSize advance;\nCTFontGetAdvancesForGlyphs( font, 0, &glyph, &advance, 1);\n\n// Get the bounds\nCGRect bounds;\nCTFontGetAdvancesForGlyphs( font, 0, &glyph, &bounds, 1);\n
Run Code Online (Sandbox Code Playgroud)\n\n

在 Safari 中输入。

\n\n

另外:左边也有同样的问题:大写L的前进是0(第一个字符),但是边界框有一个负x。因此左侧被剪掉。在那里也添加空间..(到目前为止更容易。)

\n