ios - 如何在 Objective-C (iOS) 中的图像上写文字?

标签 ios iphone uiimageview

我想以编程方式制作这样的图像:

example

我有上图和文字。我应该在图片上写文字吗?

我想做成一个完整的.png图片(图片+标签),设置为按钮的背景。

最佳答案

在图像中绘制文本并返回生成的图像:

+(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 更改为您喜欢的任何点。

要在文本后面绘制一个纯色矩形,请在行 [[UIColor whiteColor] set]; 之前添加以下内容:

[[UIColor brownColor] set];
CGContextFillRect(UIGraphicsGetCurrentContext(), 
                  CGRectMake(0, (image.size.height-[text sizeWithFont:font].height), 
                                  image.size.width, image.size.height));

我使用文本大小来计算纯色矩形的原点,但您可以将其替换为任何数字。

关于ios - 如何在 Objective-C (iOS) 中的图像上写文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6992830/

相关文章:

ios - 如何在iOS8中以原生分辨率显示自制位图

ios - CABasicAnimation 不适用于设备 (iPhone 5s)

iphone - 电池时间计算

ios - 如何以编程方式更改 UIImageView 中显示的图像?

objective-c - 序列化时 JSONKit 无法识别选择器

ios - 取消正在进行的 CloudKit 查询

iphone - 将富文本内容显示为 UIWebView 或 UILabel+CoreText

iphone - Objective-C 中的模糊日期算法

ios - 更改导航栏标题字体 - 不同

iphone - 创建水平线