Objective-C Tips & Trick - Prioregroup.com
[Objective-C] Add text to image
       
back

//
//  Created by Danilo Priore on 18/08/12.
//  Copyright (c) 2012 Prioregroup.com. All rights reserved.
//

- (UIImage*)addTextToImage:(UIImage*)img text:(NSString*)text1 XPos:(int)xpos YPos:(int)ypos fontName:(NSString*)fontName fontSize:(CGFloat)fontSize fontColor:(UIColor*)fontColor {
    
    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);
    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1);
	
    char *txt = (char*)[text1 cStringUsingEncoding:NSUTF8StringEncoding];
    char *font = (char*)[fontName cStringUsingEncoding:NSUTF8StringEncoding];
    
    CGContextSelectFont(context, font, fontSize, kCGEncodingMacRoman);
    CGContextSetTextDrawingMode(context, kCGTextFill);
    CGContextSetFillColorWithColor(context, fontColor.CGColor);
    CGContextShowTextAtPoint(context, xpos, ypos, txt, strlen(txt));
    
	CGImageRef imageRef = CGBitmapContextCreateImage(context);
	CGContextSetAllowsAntialiasing(context, YES);
	
	UIImage *result = [UIImage imageWithCGImage:imageRef];
	
	CGImageRelease(imageRef);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
	
    return result;
}






Copyright © 1996-2018 Centro Studi Informatica di Danilo Priore. All rights reserved. P.I.10149810581.
prioregroup.com