一般在用戶端做圖檔處理的數量不宜太多,因為受裝置性能的限制,如果批量的處理圖檔,将會帶來互動體驗性上的一些問題。首先讓我們來看看在圖檔上添加文字的方法、
- -(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, 44 * 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 = (charchar *)[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, 44 * 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]);
- }
對于圖檔疊加文字,和圖檔疊加圖檔,基本的原理是一樣的,建立繪圖上下文,然後在上下文中繪制圖檔或者文字,然後重新生成圖檔,以達到我們需要的效果。