简体   繁体   中英

iOS - Overlay UIImage with color on non-transparent area only?

I have a white image with transparent area in the middle like this:

在此处输入图片说明

I want to overlay it with colour (non-transparent area only) so it looks like this:

在此处输入图片说明

How can I do this?

I have looked into this answer but it overlay the whole image including the non-transparent area.

So your image is effectively a "mask". Play around with the "CGContextClipToMask" call and the above code that you referenced.

Try the following code and it gives the exact what you want.

    UIGraphicsBeginImageContextWithOptions(imgView.image.size, YES, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);
    CGContextFillRect(context, (CGRect){ {0,0}, imgView.image.size} );

    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, imgView.image.size.height);
    CGContextConcatCTM(context, flipVertical);
    CGContextDrawImage(context, (CGRect){ {0,0}, imgView.image.size }, [imgView.image CGImage]);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [imgView setImage:image];

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