CGImageCreateWithMask works great but the masked out area is black in my resulting image, how can I set it to be white?

后端 未结 4 995
别跟我提以往
别跟我提以往 2021-01-03 04:06

I\'ve masked out my image thusly:

    CGImageRef maskRef = [[UIImage imageNamed:@\"testMask2.png\"] CGImage];

CGImageRef mask = CGImageMaskCreate(CGImageGet         


        
相关标签:
4条回答
  • 2021-01-03 04:26

    I was struggling with the same issue. The solution is pretty simple: It is the best to create graphic context for masking this way:

    UIGraphicsBeginImageContextWithOptions(maskFrame.size, NO, 0.0);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect ff =  CGRectMake(0, 0, maskFrame.size.width, mask.size.height);
    CGContextClipToMask(ctx, ff, mask.CGImage);
    ....
    

    Make sure, the second parameter in UIGraphicsBeginImageContextWithOptions is set to NO (which means none-opaque context). Another benefit is that this creation function automatically scales context to retina displays.

    0 讨论(0)
  • 2021-01-03 04:30

    The image is supposed to be transparent where it's "masked out"; the colour you see will depend on what background you're drawing it on.

    (I don't remember if there's a requirement that the source image has an alpha channel.)

    It may be worth making sure that imageView.opaque = NO.

    0 讨论(0)
  • 2021-01-03 04:33

    Try this:

    imageView.opaque = NO;
    imageView.backgroundColor = [UIColor clearColor];

    Also, the image used to mask should be black and white (not transparent).

    0 讨论(0)
  • 2021-01-03 04:42

    If you are masking JPEG image which does not have alpha channel this will happen (black background instead of transparent).

    So you need to do something like this before masking:

        CGImageRef imageNoAlpha = [UIImage imageNamed:@"noAlphaImage.jpg"].CGImage;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
    
    CGFloat width = CGImageGetWidth(imageNoAlpha);
    CGFloat height = CGImageGetHeight(imageNoAlpha);
    
    CGContextRef ctxWithAlpha = CGBitmapContextCreate(nil, width, height, 8, 4*width, cs, kCGImageAlphaPremultipliedFirst);
    
    CGContextDrawImage(ctxWithAlpha, CGRectMake(0, 0, width, height), imageNoAlpha);
    
    CGImageRef imageWithAlpha = CGBitmapContextCreateImage(ctxWithAlpha);
    
    CGImageRef masked = CGImageCreateWithMask(imageWithAlpha, mask);
    

    ...

    Be sure to release created images, context and colorspace ...

    0 讨论(0)
提交回复
热议问题