我正在使用代码找到here创建一个图像,其中包含缩放到可用大小的文本:
CGFloat size = 100.0;
CGRect drawRect = CGRectMake(10, 10, 80, 25);
UILabel *myLabel = [[UILabel alloc] initWithFrame:drawRect];
myLabel.font = [UIFont fontWithName:@"HelveticaNeue-BoldItalic" size:16];
myLabel.text = "Hello text!";
myLabel.minimumScaleFactor = 0.5;
myLabel.adjustsFontSizeToFitWidth = YES;
myLabel.textAlignment = NSTextAlignmentCenter;
myLabel.backgroundColor = [UIColor clearColor];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size, size), NO, 0);
[[myLabel layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[screenshot drawInRect:drawRect];
return screenshot;
字符串
这将创建一个100x100的图像,渲染标签位于左上角:(0,0).我如何在所需的点(10,10)得到文本?
澄清一下:我希望标签是我指定的大小,水平居中,其文本根据可用大小进行缩放。
另外,[screenshot drawInRect:drawRect]
的目的是什么,因为我似乎得到了相同的结果没有它?
3条答案
按热度按时间x8goxv8g1#
回答你的具体问题...
首先,关于 “
[screenshot drawInRect:drawRect]
的目的是什么“...据推测,你从那里得到的帖子打算说这样的话:* “现在你有了一个100 x 100
UIImage
的“屏幕截图”,你可以在其他图形上下文中将其绘制到其他rect中。"*其次...
标签不是以
(10, 10)
绘制,因为您正在渲染标签的图层--其原点为(0, 0)
。如果你想以
(10, 10)
渲染,你可以在绘制之前修改层的边界:字符串
所以,如果我们运行你的代码(不知道为什么你有两个
let
语句):型
现在,您将拥有一个名为“screenshot”的100 x 100点(非像素)
UIImage
,标签为frame(10, 10)
(同样,10点不是像素)。这就是结果。。请注意,您发布的代码指定了设备主屏幕缩放因子
CGContextRef
。 我在iPhone 14 Pro上运行这个函数,它的因子为@3x,所以输出是一个300 x300 pixel 的图像,标签帧为(30,30)pixels:x1c 0d1x的数据
因为它有一个清晰的背景,这就是它在绘画应用程序中的外观。
如果我们稍微修改代码,添加颜色来填充图像rect和标签框,它看起来像这样:
的
顺便说一句,您可能希望研究一下更“现代”的
UIGraphicsImageRenderer
dfty9e192#
这很简单,只需将标签 Package 在视图中,然后捕获视图而不是标签。
字符串
之前
的数据
之后
的
oug3syen3#
插入用于初始化标签框架的矩形…
字符串
免责声明:自从我使用Objective-C已经有好几年了。
(关于
drawInRect:
的用途,这就是您在创建图像后选择使用图像的方式。你可以选择画它。如果您不需要,或者稍后在其他地方绘制,您可以删除该线)。