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) 中的图像上写文本?
基础教程推荐
- AdMob 广告未在模拟器中显示 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
