Add drop shadow to text written on UIIImage

I'm writing text onto an image like so:

    -(UIImage *)addLabelToImage:(UIImage *)img
{
    UIFont *font = [UIFont boldSystemFontOfSize:20];
    UIGraphicsBeginImageContext(img.size);
    [img drawInRect:CGRectMake(0, 0,img.size.width,img.size.height)];
    CGRect rect = CGRectMake(60, 550, img.size.width, img.size.height);
    [[UIColor whiteColor] set];
    [[NSString stringWithFormat:@"%@, %@", [[NSUserDefaults standardUserDefaults] valueForKey:@"whatever"], [[NSUserDefaults standardUserDefaults] valueForKey:@"whatever2"]] drawInRect:CGRectIntegral(rect) withFont:font]; 
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

How would I add a drop shadow to this text? I know I can just redraw the text in black shifted over a few pixels, but is there an easier way?

Cheers, George

Upvotes: 1

Views: 472

Answers (1)

omz
omz

Reputation: 53551

Before you draw your text, you can set a shadow like this:

//...
CGContextRef c = UIGraphicsGetCurrentContext();
CGSize offset = CGSizeMake(0, 1);
CGFloat blur = 2.0;
UIColor *shadowColor = [UIColor blackColor];
CGContextSetShadowWithColor(c, offset, blur, [shadowColor CGColor]);
//draw your text ...

Adjust the offset, blur and shadowColor parameters as needed to achieve the effect you want. For a sharp shadow (like on a UILabel), set blur to 0.

Upvotes: 3

Related Questions