ios圖片添加文字或者水印

http://www.tuicool.com/articles/nYNFVj   mark


一般在客戶端做圖片處理的數量不宜太多,因爲受設備性能的限制,如果批量的處理圖片,將會帶來交互體驗性上的一些問題。首先讓我們來看看在圖片上添加文字的方法、

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

對於圖片疊加文字,和圖片疊加圖片,基本的原理是一樣的,創建繪圖上下文,然後在上下文中繪製圖片或者文字,然後重新生成圖片,以達到我們需要的效果。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章