Advertisement
priore

Add text to image

Aug 19th, 2012
1,238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  Created by Danilo Priore on 18/08/12.
  3. //  Copyright (c) 2012 Prioregroup.com. All rights reserved.
  4. //
  5.  
  6. - (UIImage*)addTextToImage:(UIImage*)img text:(NSString*)text1 XPos:(int)xpos YPos:(int)ypos fontName:(NSString*)fontName fontSize:(CGFloat)fontSize fontColor:(UIColor*)fontColor {
  7.    
  8.     int w = img.size.width;
  9.     int h = img.size.height;
  10.    
  11.     CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  12.     CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
  13.    
  14.     CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
  15.     CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1);
  16.    
  17.     char *txt = (char*)[text1 cStringUsingEncoding:NSUTF8StringEncoding];
  18.     char *font = (char*)[fontName cStringUsingEncoding:NSUTF8StringEncoding];
  19.    
  20.     CGContextSelectFont(context, font, fontSize, kCGEncodingMacRoman);
  21.     CGContextSetTextDrawingMode(context, kCGTextFill);
  22.     CGContextSetFillColorWithColor(context, fontColor.CGColor);
  23.     CGContextShowTextAtPoint(context, xpos, ypos, txt, strlen(txt));
  24.    
  25.     CGImageRef imageRef = CGBitmapContextCreateImage(context);
  26.     CGContextSetAllowsAntialiasing(context, YES);
  27.    
  28.     UIImage *result = [UIImage imageWithCGImage:imageRef];
  29.    
  30.     CGImageRelease(imageRef);
  31.     CGContextRelease(context);
  32.     CGColorSpaceRelease(colorSpace);
  33.    
  34.     return result;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement