Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show Blended Layers reveals red UIImage but it does not have an alpha channel

I have an image that does not have an alpha channel - I confirmed in Finder's Get Info panel. Yet when I put it in a UIImageView which is within a UIScrollView and I enable Show Blended Layers, the image is red which indicates it's trying to apply transparency which will be a hit on performance.

How can fix this to be green so iOS knows everything in this view is fully opaque?

I tried the following but this did not remove the red color:

self.imageView.opaque = YES;
self.scrollView.opaque = YES;
like image 290
Jordan H Avatar asked May 29 '14 18:05

Jordan H


2 Answers

Swift 3x Xcode 9x

func optimizedImage(from image: UIImage) -> UIImage {
    let imageSize: CGSize = image.size
    UIGraphicsBeginImageContextWithOptions(imageSize, true, UIScreen.main.scale)
    image.draw(in: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
    let optimizedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return optimizedImage ?? UIImage()
}
like image 95
Abdul Karim Avatar answered Nov 04 '22 17:11

Abdul Karim


By default, UIImage instances are rendered in a Graphic Context that includes alpha channel. To avoid it, you need to generate another image using a new Graphic Context where opaque = YES.

- (UIImage *)optimizedImageFromImage:(UIImage *)image
{
    CGSize imageSize = image.size;
    UIGraphicsBeginImageContextWithOptions( imageSize, opaque, scale );
    [image drawInRect: CGRectMake( 0, 0, imageSize.width, imageSize.height )];
    UIImage *optimizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return optimizedImage;
}
like image 36
Gustavo Barbosa Avatar answered Nov 04 '22 16:11

Gustavo Barbosa