如何删除UIImage背景颜色并使其透明?

时间:2011-10-03 09:17:57

标签: ios cocoa-touch uikit uiimage

我想删除UIImage背景颜色并使其透明......

我试过这个,但下面的代码只是将白色背景颜色改为黑色。

   UIImage* createColorMaskedImage(UIImage* originalImage){
float maskingColors[6] = {0xEE, 0xFF, 0xEE, 0xFF, 0xEE, 0xFF};
CGImageRef maskedImageRef = CGImageCreateWithMaskingColors(originalImage.CGImage,     maskingColors);
UIImage* maskedImage = [UIImage imageWithCGImage:maskedImageRef];
CGImageRelease(maskedImageRef);
return maskedImage;
}


UIImage *watchImage = [UIImage imageNamed:@"watch2.jpg"];
// Mask image
colorMaskImage_ = createColorMaskedImage(watchImage);
//create image view and set its poistion.
UIImageView* maskImageView = [[UIImageView alloc] initWithImage:colorMaskImage_];
CGRect frame = maskImageView.frame;
frame.origin = CGPointMake(80,60);
maskImageView.frame = frame;
maskImageView.backgroundColor = [UIColor clearColor];
[self.view addSubview:maskImageView];
[maskImageView release];

2 个答案:

答案 0 :(得分:0)

你的watch2.jpg可能没有alpha值,这会让它有透明区域。

答案 1 :(得分:0)

快速版本

func makeTransparent(image: UIImage) -> UIImage? {
    guard let rawImage = image.cgImage else { return nil}
    let colorMasking: [CGFloat] = [255, 255, 255, 255, 255, 255]
    UIGraphicsBeginImageContext(image.size)
    
    if let maskedImage = rawImage.copy(maskingColorComponents: colorMasking),
        let context = UIGraphicsGetCurrentContext() {
        context.translateBy(x: 0.0, y: image.size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.draw(maskedImage, in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return finalImage
    }
    
    return nil
}