How to set the opacity/alpha of a UIImage? How to set the opacity/alpha of a UIImage? ios ios

How to set the opacity/alpha of a UIImage?


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();    UIGraphicsEndImageContext();    return newImage;}


Set the opacity of its view it is showed in.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"SomeName.png"]];imageView.alpha = 0.5; //Alpha runs from 0.0 to 1.0

Use this in an animation. You can change the alpha in an animation for an duration.

[UIView beginAnimations:nil context:NULL];[UIView setAnimationDuration:1.0];//Set alpha[UIView commitAnimations];


Based on Alexey Ishkov's answer, but in Swift

I used an extension of the UIImage class.

Swift 2:

UIImage Extension:

extension UIImage {    func imageWithAlpha(alpha: CGFloat) -> UIImage {        UIGraphicsBeginImageContextWithOptions(size, false, scale)        drawAtPoint(CGPointZero, blendMode: .Normal, alpha: alpha)        let newImage = UIGraphicsGetImageFromCurrentImageContext()        UIGraphicsEndImageContext()        return newImage    }}

To use:

let image = UIImage(named: "my_image")let transparentImage = image.imageWithAlpha(0.5)

Swift 3/4/5:

Note that this implementation returns an optional UIImage. This is because in Swift 3 UIGraphicsGetImageFromCurrentImageContext now returns an optional. This value could be nil if the context is nil or what not created with UIGraphicsBeginImageContext.

UIImage Extension:

extension UIImage {    func image(alpha: CGFloat) -> UIImage? {        UIGraphicsBeginImageContextWithOptions(size, false, scale)        draw(at: .zero, blendMode: .normal, alpha: alpha)        let newImage = UIGraphicsGetImageFromCurrentImageContext()        UIGraphicsEndImageContext()        return newImage    }}

To use:

let image = UIImage(named: "my_image")let transparentImage = image?.image(alpha: 0.5)