CGImage Masking stopped working on iOS 12

走远了吗. 提交于 2021-02-09 15:41:20

问题


I've got a method for masking a B&W image by cutting out (i.e. making transparent) any pixels that are above or below a certain brightness. The result would be the same B&W image, but with everything above 70% or below 25% brightness (or whatever you choose) changed to transparent.

It was working perfectly on iOS 11, but it broke on iOS 12. It now returns the original, solid image with no modifications every time.

-(UIImage*)imageWithLumaMaskFromDark:(CGFloat)lumaFloor toLight:(CGFloat)lumaCeil {
    // inputs range from 0 - 255
    CGImageRef rawImageRef = self.CGImage;

    const CGFloat colorMasking[6] = {lumaFloor, lumaCeil, lumaFloor, lumaCeil, lumaFloor, lumaCeil};

    UIGraphicsBeginImageContext(self.size);
    CGImageRef maskedImageRef = CGImageCreateWithMaskingColors(rawImageRef, colorMasking);
    {
        //if in iphone
        CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, self.size.height);
        CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);
    }

    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, self.size.width, self.size.height), maskedImageRef);
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    CGImageRelease(maskedImageRef);
    UIGraphicsEndImageContext();
    return result;
}

I'm an experienced iOS dev but a complete CGImage/CGContext noob. Can anyone help me figure out what could have broken with this method in iOS 12, and what I can do to fix it?


回答1:


Based on this answer to a related question, apparently I needed to convert it to an uncompressed JPG before attempting the mask, to remove any alpha channels.

The thing that changed in iOS 12 was, per their Release Notes, "Various Core Graphics calls have been hardened against continuing with invalid parameters. In iOS 12, these calls may now return nil or return early."

So the transparency that was included before iOS 12 worked fine, but with iOS 12 stopped working. The linked answer above works great.



来源:https://stackoverflow.com/questions/54845394/cgimage-masking-stopped-working-on-ios-12

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!