开发者

How to remove UIImage Background color and make it transparent?

I wanted to remove UIImage background color and make it transparent...

I tried this but the following code just changing White background color into Black Color.

   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:m开发者_Python百科askImageView];
[maskImageView release];


Swift version

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
}


Your watch2.jpg probably doesn't have alpha values, which would let it have transparent areas.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜