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

查看:259
本文介绍了如何在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天全站免登陆