如何在 UIView 上绘制一个 NSString 数组,它们之间没有任何前导空格并占据整个矩形?
Posted
技术标签:
【中文标题】如何在 UIView 上绘制一个 NSString 数组,它们之间没有任何前导空格并占据整个矩形?【英文标题】:How to draw an array of NSStrings on as UIView without any leading space between them and occupies the entire rect? 【发布时间】:2016-04-18 04:50:13 【问题描述】:我想在 UIView 上以this 的形式绘制一个不同字体大小的字符串数组。我已经计算了要绘制的每个字符串所需的高度。示例中的字符串数组是 "Enter some text", "that", "will fit", "the rect"。我计算高度如下,
@implementation NSString (Additions)
- (CGFloat)heightForFont:(UIFont *)font
NSAttributedString *attrString = [[NSAttributedString alloc]initWithString:self attributes:@NSFontAttributeName:font];
CTLineRef line = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)attrString);
CGFloat ascent, descent, leading;
CGFloat width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
CGFloat height = ascent + descent + leading;
return height;
然后我尝试在 UIView 中绘制字符串,如下所示:
- (void)drawStringArray:(NSArray *)splittedStringArray maxYoFString:(CGFloat)maxY rect:(CGRect)rect fontsDict:(NSMutableDictionary *)fontsDict
//Alter X origin if scaled
CGFloat originX = rect.origin.x;
CGRect drawRect = rect;
drawRect.origin.x = originX;
drawRect.origin.y = 0.0;
CGFloat heightForString = 0.0;
for (int i = 0; i < splittedStringArray.count; i++)
NSString *string = splittedStringArray[i];
UIFont *font = [fontsDict objectForKey:string];
if(i < splittedStringArray.count -1)
heightForString = [string heightForFont:font];
[string drawInRect:rect withAttributes:@
NSFontAttributeName : font,
NSForegroundColorAttributeName :self.random.currentTextColor
];
drawRect.origin.y += heightForString;
但是在两行之间总是有一个空格。我想绘制没有任何前导空格的字符串。current image, expected image
【问题讨论】:
【参考方案1】:一个简单的解决方案是修补字体文件本身并确定其行高。在此处查看操作方法。
http://mbauman.net/geek/2009/03/15/minor-truetype-font-editing-on-a-mac/
【讨论】:
以上是关于如何在 UIView 上绘制一个 NSString 数组,它们之间没有任何前导空格并占据整个矩形?的主要内容,如果未能解决你的问题,请参考以下文章