简体   繁体   中英

CGImageCreateWithMaskingColors Does Not Mask on Apple Watch in WKInterfaceImage

I've long since had a snippet of code in my iPhone app that attempts to mask the white background from some JPEG images. Today, this message still works well on iPhone, but does not mask whatsoever on Apple Watch. The code runs on the expected successful (non- NULL ) path, but no masking is performed. Even if I change the maskingColors array to the range 0.0, 255.0 for each component, no masking is performed (this same change on iPhone completely masks the image) when displayed in a WKInterfaceImage (with setImage: ).

PNG images with an alpha channel stored in an asset catalog seem to display properly on Apple Watch in a WKInterfaceImage .

Is CGImageCreateWithMaskingColors not safe for Apple Watch?

- (UIImage *)imageWithBackgroundRemovedWithImageData:(NSData *)imageData
{
    CGImageRef originalImage = [UIImage imageWithData:imageData].CGImage;

    /* Only attempt for RGB images */
    if (CGColorSpaceGetModel(CGImageGetColorSpace(originalImage)) != kCGColorSpaceModelRGB)
        return ([UIImage imageWithData:imageData]);

    /* Mask 10 shades of "white" */
    static const CGFloat maskingColors[] = {245.0, 255.0, 245.0, 255.0, 245.0, 255.0};
    CGImageRef transparentImageRef = CGImageCreateWithMaskingColors(originalImage, maskingColors);
    if (transparentImageRef == NULL)
        return ([UIImage imageWithData:imageData]);

    UIImage *transparentImage = [UIImage imageWithCGImage:transparentImageRef];
    CGImageRelease(transparentImageRef);
    return (transparentImage);
}

This appears to be an issue that has existed since iOS 7. See this post for more details: CGImageCreateWithMaskingColors Doesn't Work with iOS7

Using that logic, I've modified your code as follows to produce the intended result:

UIGraphicsBeginImageContextWithOptions(transparentImage.size, NO, 1.0);
[transparentImage drawInRect:CGRectMake(0, 0, transparentImage.size.width, transparentImage.size.height)];
UIImage *anotherRendition = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return (anotherRendition);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM