天天看點

IOS 圖檔水印或者文字

一般在用戶端做圖檔處理的數量不宜太多,因為受裝置性能的限制,如果批量的處理圖檔,将會帶來互動體驗性上的一些問題。首先讓我們來看看在圖檔上添加文字的方法、

  1. -(UIImage *)addText:(UIImage *)img text:(NSString *)text1   
  2. {   
  3. //上下文的大小   
  4. int w = img.size.width;   
  5. int h = img.size.height;   
  6. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();//建立顔色   
  7. //建立上下文   
  8. CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 44 * w, colorSpace, kCGImageAlphaPremultipliedFirst);   
  9. CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);//将img繪至context上下文中   
  10. CGContextSetRGBFillColor(context, 0.0, 1.0, 1.0, 1);//設定顔色   
  11. char* text = (charchar *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];   
  12. CGContextSelectFont(context, "Georgia", 30, kCGEncodingMacRoman);//設定字型的大小   
  13. CGContextSetTextDrawingMode(context, kCGTextFill);//設定字型繪制方式   
  14. CGContextSetRGBFillColor(context, 255, 0, 0, 1);//設定字型繪制的顔色   
  15. CGContextShowTextAtPoint(context, w/2-strlen(text)*5, h/2, text, strlen(text));//設定字型繪制的位置   
  16. //Create image ref from the context   
  17. CGImageRef imageMasked = CGBitmapContextCreateImage(context);//建立CGImage   
  18. CGContextRelease(context);   
  19. CGColorSpaceRelease(colorSpace);   
  20. return [UIImage imageWithCGImage:imageMasked];//獲得添加水印後的圖檔   
  21. }  

在上面的方法中,我們可以看到,我們可以通過将圖檔和文字繪制到同一個上下文中,并且重新生成圖檔,所獲得圖檔就是包括圖檔和文字。

另外在一些項目中我們可能還回用到圖檔疊加,比如打水印等功能,這種功能相對上面給圖檔添加文字更容易,隻是在上下文中,繪制兩張圖檔,然後重新生成,以達到圖檔的疊加、代碼如下:

  1. -(UIImage *)addImageLogo:(UIImage *)img text:(UIImage *)logo   
  2. {   
  3. //get image width and height   
  4. int w = img.size.width;   
  5. int h = img.size.height;   
  6. int logoWidth = logo.size.width;   
  7. int logoHeight = logo.size.height;   
  8. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();   
  9. //create a graphic context with CGBitmapContextCreate   
  10. CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 44 * w, colorSpace, kCGImageAlphaPremultipliedFirst);   
  11. CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);   
  12. CGContextDrawImage(context, CGRectMake(w-logoWidth, 0, logoWidth, logoHeight), [logo CGImage]);   
  13. CGImageRef imageMasked = CGBitmapContextCreateImage(context);   
  14. CGContextRelease(context);   
  15. CGColorSpaceRelease(colorSpace);   
  16. return [UIImage imageWithCGImage:imageMasked];   
  17. // CGContextDrawImage(contextRef, CGRectMake(100, 50, 200, 80), [smallImg CGImage]);   
  18. }  

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