简体   繁体   English

Objective-C-文本基线位于左下角

[英]Objective-C - Text baseline on lower left corner

When drawing a string in IOS, by default the text is baselined by the upper left corner. 在IOS中绘制字符串时,默认情况下,文本以左上角为基线。 This can cause problems when using multiple strings with different font-sizes with the same y-coordinate. 当使用多个具有相同y坐标的不同字体大小的字符串时,这可能会导致问题。

Question; 题;
How do I baseline a string by the lower left corner of the first row . 如何在第一行的左下角建立字符串基线

在此处输入图片说明

How do I achieve this? 我该如何实现?

Br,
Tim 提姆

I finally found the solution to my problem. 我终于找到了解决我问题的方法。
By subtracting the UIFont ascender property from the rect.origin.y, I could baseline the text to the lower left corner. 通过从rect.origin.y中减去UIFont的ascender属性,我可以将文本基线设置到左下角。

Citing the UIFont documentation of the ascender property: 引用ascender属性的UIFont文档:

"The top y-coordinate, offset from the baseline, of the receiver's longest ascender." “距离接收器最长的上升点的基线偏移的最高y坐标。” https://developer.apple.com/library/ios/documentation/uikit/reference/UIFont_Class/Reference/Reference.html#//apple_ref/occ/instp/UIFont/ascender https://developer.apple.com/library/ios/documentation/uikit/reference/UIFont_Class/Reference/Reference.html#//apple_ref/occ/instp/UIFont/ascender

- (void)drawTextBaseLined:(NSString *)text
                     rect:(CGRect)rect
                     font:(UIFont *)font
{
  if ([text length] == 0) return false;

  NSDictionary *attributes = @{NSFontAttributeName : font};

  rect.origin.y -= font.ascender;
  [text drawWithRect:rect
             options:NSStringDrawingUsesLineFragmentOrigin
          attributes:attributes
             context:nil];
}

This method will work with one or multiple lines of text and with different font-sizes. 此方法适用于一行或多行文本以及不同的字体大小。 I hope my solution helps someone else too. 我希望我的解决方案也能帮助其他人。

Br,
Tim 提姆

Use - (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context; 使用- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context;

When you have the height of your label just do the math to choose the right origin of it to have the below left corner always at the same place. 当您具有标签的高度时,只需进行数学运算即可选择标签的正确原点,以使左下角始终位于同一位置。

NSDictionary * attributes = @{NSFontAttributeName:[UIFont systemFont]};

CGRect rect = [[NSString string] boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];

If you want your label below left corner to be always at 50pix the origin of your label will be at (50 - rect.size.height). 如果希望左下角的标签始终为50pix,则标签的原点将为(50-rect.size.height)。

Change the size to adapt to your constraints. 更改大小以适应您的约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM