How to write text on image in Objective-C (iOS)?(如何在 Objective-C (iOS) 中的图像上写文本?)
问题描述
我想以编程方式制作这样的图像:
I want to make an image like this programmatically:
我有上面的图片和文字.我应该在图片上写文字吗?
I have the upper image and text with me. Should I write text on the image?
我想把它做成一个完整的.png图片(图片+标签),并将其设置为按钮的背景.
I want to make it a complete .png image(image + label) and set it as the background of the button.
推荐答案
在图像内绘制文本并返回结果图像:
Draw text inside an image and return the resulting image:
+(UIImage*) drawText:(NSString*) text
inImage:(UIImage*) image
atPoint:(CGPoint) point
{
UIFont *font = [UIFont boldSystemFontOfSize:12];
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height);
[[UIColor whiteColor] set];
[text drawInRect:CGRectIntegral(rect) withFont:font];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
用法:
// note: replace "ImageUtils" with the class where you pasted the method above
UIImage *img = [ImageUtils drawText:@"Some text"
inImage:img
atPoint:CGPointMake(0, 0)];
将图像内文本的原点从 0,0 更改为您喜欢的任何点.
Change the origin of the text inside the image from 0,0 to whatever point you like.
要在文本后面绘制一个纯色矩形,请在 [[UIColor whiteColor] set];
:
To paint a rectangle of solid color behind the text, add the following before the line [[UIColor whiteColor] set];
:
[[UIColor brownColor] set];
CGContextFillRect(UIGraphicsGetCurrentContext(),
CGRectMake(0, (image.size.height-[text sizeWithFont:font].height),
image.size.width, image.size.height));
我正在使用文本大小来计算纯色矩形的原点,但您可以将其替换为任意数字.
I'm using the text size to calculate the origin for the solid color rectangle, but you can replace it with any number.
这篇关于如何在 Objective-C (iOS) 中的图像上写文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Objective-C (iOS) 中的图像上写文本?


- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- URL编码Swift iOS 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- UITextView 内容插图 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- GPS状态的广播接收器? 2022-01-01