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];//得到添加水印後的圖片
}字體

在上面的方法中,咱們能夠看到,咱們能夠經過將圖片和文字繪製到同一個上下文中,而且從新生成圖片,所得到圖片就是包括圖片和文字。圖片

 

另外在一些項目中咱們可能還回用到圖片疊加,好比打水印等功能,這種功能相對上面給圖片添加文字更容易,只是在上下文中,繪製兩張圖片,而後從新生成,以達到圖片的疊加、代碼以下: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

相關文章
相關標籤/搜索