Marty Marty - 1 year ago 217
iOS Question

How to set the opacity/alpha of a UIImage?

I know you can do this with a UIImageView, but can it be done to a UIImage? I want to have the animation images array property of a UIImageView to be an array of the same image but with different opacities. Thoughts?

Answer Source

I just needed to do this, but thought Steven's solution would be slow. This should hopefully use graphics HW. Create a category on UIImage:

- (UIImage *)imageByApplyingAlpha:(CGFloat) alpha {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);

    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);

    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);

    CGContextSetAlpha(ctx, alpha);

    CGContextDrawImage(ctx, area, self.CGImage);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();


    return newImage;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download