UIImage from UIColor with alpha

Rameez Hussain picture Rameez Hussain · Apr 8, 2013 · Viewed 9.6k times · Source

I am trying to create a UIImage from this UIColor value I have. The UIImage is being created, but the alpha value is lost. The image remains opaque. I am using the following code:

@implementation GetImage

+ (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size
{
    UIImage *img = nil;

    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,
                               color.CGColor);
    CGContextFillRect(context, rect);

    img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;
}

@end

Which I call like so:

-(void) setButtonColours{

    UIImage *img1, *img2;

    UIColor *red = [UIColor colorWithRed:205.0/255.0 green:68.0/255.0 blue:51.0/255.0 alpha:1.0],
    *blue = [UIColor colorWithRed:71.0/255.0 green:97.0/255.0 blue:151.0/255.0 alpha:1.0];

    img1 = [GetImage imageWithColor: blue andSize: self.dummyButton.frame.size];

    img2 = [GetImage imageWithColor: red andSize: self.dummyButton.frame.size];

    [self.dummyButton setBackgroundImage: img1 forState:UIControlStateNormal];
    [self.dummyButton setBackgroundImage: img2 forState:UIControlStateSelected];

}

Any idea what I'm missing?

Answer

Felix picture Felix · Apr 8, 2013

You are creating an opaque image context.

Replace this line:

UIGraphicsBeginImageContext(rect.size);

with:

UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);