ios图片添加文字或者水印

  在项目中,我们会对图片做一些处理,但是我们要记住,一般在客户端做图片处理的数量不宜太多,因为受设备性能的限制,如果批量的处理图片,将会带来交互体验性上的一些问题。首先让我们来看看在图片上添加文字的方法、

  

-(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];//获得添加水印后的图片
}

在上面的方法中,我们可以看到,我们可以通过将图片和文字绘制到同一个上下文中,并且重新生成图片,所获得图片就是包括图片和文字。

 

另外在一些项目中我们可能还回用到图片叠加,比如打水印等功能,这种功能相对上面给图片添加文字更容易,只是在上下文中,绘制两张图片,然后重新生成,以达到图片的叠加、代码如下:

-(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]);
}

对于图片叠加文字,和图片叠加图片,基本的原理是一样的,创建绘图上下文,然后在上下文中绘制图片或者文字,然后重新生成图片,以达到我们需要的效果。  

posted on 2014-04-22 23:59  故乡的守望者  阅读(1382)  评论(0编辑  收藏  举报