[iOS]設定UIImage的透明度

平常都是透過UIImageView設定背景色的透明度,但如果要圖片本身帶有透明度效果,可參考How to set the opacity/alpha of a UIImage?這篇文章的作法,參考Nick H247的做法修改如下:

- (UIImage *)imageByApplyingAlpha:(UIImageView *)imageView alpha:(CGFloat) alpha {
    UIGraphicsBeginImageContextWithOptions(imageView.frame.size, NO, 0.0f);
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height);
    
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);
    
    //CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
    
    CGContextSetAlpha(ctx, alpha);
    
    CGContextDrawImage(ctx, area, imageView.image.CGImage);
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

沒有留言: