Adding text over an image on Xcode

13,980

Solution 1

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;
}

Solution 2

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);
Share:
13,980
hafedh
Author by

hafedh

Updated on June 19, 2022

Comments

  • hafedh
    hafedh almost 2 years

    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.