Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding text over an image on Xcode

I want to make an iphone application similar to some greeting cards application, where I could write text over some pre prepared background images(cards).

  • How can I write this text?
  • How to save the background image+the text on one image file ?

Thanks.

like image 710
hafedh Avatar asked Nov 15 '11 15:11

hafedh


2 Answers

Here is a method that burns a string into an image. You can tweak the font size and other parameters to configure it to your liking.

/* Creates an image with a home-grown graphics context, burns the supplied string into it. */
- (UIImage *)burnTextIntoImage:(NSString *)text :(UIImage *)img {

UIGraphicsBeginImageContext(img.size);

CGRect aRectangle = CGRectMake(0,0, img.size.width, img.size.height);
[img drawInRect:aRectangle];

[[UIColor redColor] set];           // set text color
NSInteger fontSize = 14;
if ( [text length] > 200 ) {
    fontSize = 10;
}
UIFont *font = [UIFont boldSystemFontOfSize: fontSize];     // set text font

[ text drawInRect : aRectangle                      // render the text
         withFont : font
    lineBreakMode : UILineBreakModeTailTruncation  // clip overflow from end of last line
        alignment : UITextAlignmentCenter ];

UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext();   // extract the image
UIGraphicsEndImageContext();     // clean  up the context.
return theImage;
}
like image 188
Rayfleck Avatar answered Oct 13 '22 00:10

Rayfleck


Thanks Rayfleck! It worked.

To add optional compatibility with retina displays (fixes choppy letters during '@2x' version of image scale up):

replace:

UIGraphicsBeginImageContext(img.size);

with conditional:

if (UIGraphicsBeginImageContextWithOptions != NULL)
    UIGraphicsBeginImageContextWithOptions(img.size,NO,0.0);
else
    UIGraphicsBeginImageContext(img.size);
like image 36
Rob Avatar answered Oct 13 '22 01:10

Rob