如何在 Objective-C (iOS) 中的图像上写文本? [英] How to write text on image in Objective-C (iOS)?

查看:22
本文介绍了如何在 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) 中的图像上写文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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