在项目中,咱们会对图片作一些处理,可是咱们要记住,通常在客户端作图片处理的数量不宜太多,由于受设备性能的限制,若是批量的处理图片,将会带来交互体验性上的一些问题。首先让咱们来看看在图片上添加文字的方法、性能
-(UIImage *)addText:(UIImage *)img text:(NSString *)text1
{
//上下文的大小
int w = img.size.width;
int h = img.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();//建立颜色
//建立上下文
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);//将img绘至context上下文中
CGContextSetRGBFillColor(context, 0.0, 1.0, 1.0, 1);//设置颜色
char* text = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];
CGContextSelectFont(context, "Georgia", 30, 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];//得到添加水印后的图片
}字体
在上面的方法中,咱们能够看到,咱们能够经过将图片和文字绘制到同一个上下文中,而且从新生成图片,所得到图片就是包括图片和文字。图片
另外在一些项目中咱们可能还回用到图片叠加,好比打水印等功能,这种功能相对上面给图片添加文字更容易,只是在上下文中,绘制两张图片,而后从新生成,以达到图片的叠加、代码以下:ip
-(UIImage *)addImageLogo:(UIImage *)img text:(UIImage *)logo
{
//get image width and height
int w = img.size.width;
int h = img.size.height;
int logoWidth = logo.size.width;
int logoHeight = logo.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//create a graphic context with CGBitmapContextCreate
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
CGContextDrawImage(context, CGRectMake(w-logoWidth, 0, logoWidth, logoHeight), [logo CGImage]);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:imageMasked];
// CGContextDrawImage(contextRef, CGRectMake(100, 50, 200, 80), [smallImg CGImage]);
}图片处理
对于图片叠加文字,和图片叠加图片,基本的原理是同样的,建立绘图上下文,而后在上下文中绘制图片或者文字,而后从新生成图片,以达到咱们须要的效果。 rem