使用 UIFont 时处理点或像素
我试图在我的drawRect:(CGRect)方法中将一个字符串定位在CGRect的垂直中心。
CGRect 有这样的大小:
CGRect rect = CGRectMake(0.0f, 0.0f, rectWidth, rectHeight);
为了绘制字符串,使其居中,我首先尝试了这个:
CGFloat diffHeightRectAndFont = rectHeight - font.capHeight;
[str drawAtPoint:CGPointMake(0.0f, diffHeightRectAndFont * 0.5f) withFont:font];
我首先假设会找到我的矩形和字体之间的高度差异,然后将字体偏移该高度的一半应该给出在“甜蜜点”。
然而,capHeight 的单位是磅,而 rectHeight 的单位是像素,因此该解决方案适用于尺寸范围为 12-15 的字体。之后,差异开始将字符串定位在矩形之外。
我反复讨论了几次,结果证明,一致地正确定位字符串的唯一方法是这个“hack”,它是有效的,但不会为代码的可读性带来奇迹:
CGFloat diffHeightRectAndFont = rectHeight - [[NSString stringWithString:@"F"] sizeWithFont:font].height;
是否有更直接的方法使用特定字体获取大写字母的像素高度?
提前谢谢您:)
I was trying to position a string in the vertical center of a CGRect in my drawRect:(CGRect) method.
The CGRect has this size:
CGRect rect = CGRectMake(0.0f, 0.0f, rectWidth, rectHeight);
To draw the string so that it is centered I tried this first:
CGFloat diffHeightRectAndFont = rectHeight - font.capHeight;
[str drawAtPoint:CGPointMake(0.0f, diffHeightRectAndFont * 0.5f) withFont:font];
This I first assumed would find the difference in height between my rect and font, then offsetting the font by half this height should give a y position in the "sweet spot".
However, the capHeight is in points and the rectHeight in pixels, so this solution kind of worked for fonts in the size range 12-15. After that the difference started to position the string outside the rect.
I went over this a few times and the only way to consistently position the string correctly turned out to be this 'hack', which is valid but does not do wonders for the readability of the code:
CGFloat diffHeightRectAndFont = rectHeight - [[NSString stringWithString:@"F"] sizeWithFont:font].height;
Is there a more direct way of obtaining the pixel height of a capital letter using a specific font?
Thank you in advance:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道有点晚了。但尽管如此,我的回答还是帮助了别人。
NSString 有一个 sizeWithFont: 方法(记录在 此处< /a>)我认为可以用于此目的。它返回一个 CGSize 结构,因此您可以执行类似于以下操作的操作来查找标签内文本的高度。
CGSize textSize = [[标签文本] sizeWithFont:[标签字体]];
CGFloat heightOfStringWithSpecifiedFont = textSize.height;
UILabel 有一个字体属性,您可以使用它来动态获取标签的字体详细信息,就像我上面所做的那样。
希望这有帮助:)
I know its a bit late. but nevertheless my answer my help someone else.
NSString has a sizeWithFont: method (documented here) that I think can be used for this. It returns a CGSize structure, so you could do something similar to the following to find the height of the text inside your label.
CGSize textSize = [[label text] sizeWithFont:[label font]];
CGFloat heightOfStringWithSpecifiedFont = textSize.height;
UILabel has a font property that you can use to dynamically get the font details for your label as I'm doing above.
Hope this helps :)