简体   繁体   English

如何在iOS中对黑色透明图像进行颜色填充?

[英]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. 例如,在iOS工具栏中,您可以拖动自己的.png,它是不透明的黑色和透明,并自动添加iOS蓝色光泽。

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. 我想通过使用代码着色来减少我在应用程序中保存的.png版本的数量。

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 从iOS 7开始,您现在可以使用单一颜色对黑色 (灰度)/透明图像进行着色

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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