Objective-C在图片上添加文字,请使用如下方法:
/**
在图片上添加文字,只支持英文,如果想添加其他文字,请看下面的方法
@param image 图片
@param string 要添加的文字
@return 新的图片
*/
-(UIImage *)addText:(UIImage *)image text:(NSString *)string
{
//上下文的大小
int w = image.size.width;
int h = image.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();//创建颜色
//创建上下文
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 44 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), image.CGImage);//将img绘至context上下文中
CGContextSetRGBFillColor(context, 0.0, 1.0, 1.0, 1);//设置颜色
char* text = (char *)[string cStringUsingEncoding:NSASCIIStringEncoding];
CGContextSelectFont(context, "Georgia", 50, kCGEncodingMacRoman);//设置字体的大小
CGContextSetTextDrawingMode(context, kCGTextFill);//设置字体绘制方式
CGContextSetRGBFillColor(context, 255, 0, 0, 1);//设置字体绘制的颜色
CGContextShowTextAtPoint(context, w/2-strlen(text)*5, h/2, text, strlen(text));//设置字体绘制的位置
//Create image ref from the context
CGImageRef imageMasked = CGBitmapContextCreateImage(context);//创建CGImage
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:imageMasked];//获得添加水印后的图片
}
Objective-C在图片上添加图片,请使用如下方法:
/**
在一张图片上添加logo或者水印;
添加文字也可以这么做,让美工做一张文字图片即可
warn 不支持jpg的图片
@param image 原始的图片
@param logoImage 要添加的logo
@return 返回一张新的图片
*/
-(UIImage *)addImageLogo:(UIImage *)image text:(UIImage *)logoImage
{
//原始图片的宽和高,可以根据需求自己定义
CGFloat w = self.view.frame.size.width;
CGFloat h = self.view.frame.size.height;
//logo的宽和高,也可以根据需求自己定义
CGFloat logoWidth = logoImage.size.width;
CGFloat logoHeight = logoImage.size.height;
//绘制
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 44 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), image.CGImage);
//绘制的logo位置,可自己调整
CGContextDrawImage(context, CGRectMake(w-logoWidth-10, 10, logoWidth, logoHeight), [logoImage CGImage]);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:imageMasked];
}