iOS - 如何找到与给定的CGRect相同的高度正确的字体大小(以点为单位)? [英] iOS - How to find the right font size (in points) with the same height as a given CGRect?

查看:204
本文介绍了iOS - 如何找到与给定的CGRect相同的高度正确的字体大小(以点为单位)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题几乎可以解释它。我有一个图像,我正在绘制文本。我希望文本的大小根据图像的大小,并希望找到一种方法来获得一个字体的高度只是比图像本身短一点。



  

NSString * string = @要呈现的字符串;
CGRect rect = imageView.frame;

UIFont * font = [UIFont fontWithSize:12.0]; //找到12.0pt字体的高度
CGSize size = [string sizeWithFont:font];
float pointsPerPixel = 12.0 / size.height; //计算比例
//或者:
// float pixelsPerPoint = size.height / 12.0;
float desiredFontSize = rect.size.height * pointsPerPixel;
//或者:
// float desiredFontSize = rect.size.height / pixelsPerPoint;

desiredFontSize 将包含以磅为单位的字体大小其中的高度与指定矩形的高度完全相同。你可能要乘以0.8,使字体比矩形的实际尺寸稍微小一点,以使它看起来很好。


Heading pretty much explains it. I have an image that I'm drawing text on. I want the text to be sized according to the size of the image and want to find a way to get a height for the font that is just a little shorter than the image itself.

解决方案

OK, so for everyone who thinks an iteration is not avoidable:

NSString *string = @"The string to render";
CGRect rect = imageView.frame;

UIFont *font = [UIFont fontWithSize:12.0]; // find the height of a 12.0pt font
CGSize size = [string sizeWithFont:font];
float pointsPerPixel = 12.0 / size.height; // compute the ratio
// Alternatively:
// float pixelsPerPoint = size.height / 12.0;
float desiredFontSize = rect.size.height * pointsPerPixel;
// Alternatively:
// float desiredFontSize = rect.size.height / pixelsPerPoint;

desiredFontSize will contain the font size in points of which the height is exactly the same as the height of the specified rectangle. You may want to multiply it by, say, 0.8 to make the font a bit smaller than the rect's actual size to make it look good.

这篇关于iOS - 如何找到与给定的CGRect相同的高度正确的字体大小(以点为单位)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆