简体   繁体   中英

How to color-fill a black and transparent image in iOS?

For example, in the iOS toolbar, you drag in your own .png which is opaque black and transparent, and it automatically adds the iOS blue gloss.

However, I'd like to know how to do this yourself, but just solid colors will do.

For example, if you had this image: 例

What would you do to make that entire solid, pink, or blue, or grey? I want to cut down on the number of versions of .png's I save in my app by colorizing them with code.

Thank you!

This should do it for you:

- (UIImage *)colorImage:(UIImage *)origImage withColor:(UIColor *)color
{
    UIGraphicsBeginImageContextWithOptions(origImage.size, YES, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, (CGRect){ {0,0}, origImage.size} );

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

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

    return image;
}

As of iOS 7 you can now colour black (greyscale) / transparent images with a single colour like so

UIImage *image = [UIImage imageNamed:@"myImage.png"];
UIImageView *imageView = [[UIImageView alloc]initWithImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]];
imageView.tintColor = [UIColor redColor];

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