使图片显示成相应颜色的方法

把图片直接渲染成相应的颜色(此方法我是定义在UIImage的类别中的)

/**
 把UIImage对象渲染成相应的颜色

 @param color 颜色
 @return UIImage对象
 */
- (UIImage *)tintColor:(UIColor *)color
{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, self.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextClipToMask(context, rect, self.CGImage);
    [color setFill];
    CGContextFillRect(context, rect);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

最开始,我是使用另外一种方式将图片显示成需求颜色的,如下:

//下面只是创建可以一个ImageView,在上面显示一张图片,需求是将图片显示成orange颜色
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
imageView.center = self.view.center;
//***需要设置imageView的'tintColor'属性为最终渲染颜色
imageView.tintColor = [UIColor orangeColor];
[self.view addSubview:imageView];
//对于image来说,也需要设置一个相应的属性才能最终显示成需求颜色
//即'imageWithRenderingMode:'方法
UIImage *image = [UIImage imageNamed:@"ic_contact_list_hint"];
image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
//设置imageView的'image'属性即可
imageView.image = image;

个人看来,还是直接用第一种方法来的更加直观一些,也不需要设置那么多的属性,比较方便,当然具体的区别和适用场景没有研究过,还请大家多指点。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,560评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,257评论 4 61
  • 心中一直有个声音,想要写出我的生命感受。最开始不为分享,只为表达自己的感悟,留下印记。再后来,也许想...
    萝丝去散步阅读 281评论 0 3
  • 我们大学有一对同学成为了夫妻,男的又帅又优秀,女的高挑美丽。 我们都觉得天生一对,对他们充满了羡慕嫉妒恨。 结婚后...
    6c676d940028阅读 271评论 0 0
  • 《世法哲言》(六十五) 唯美者者乃相对之论,方法之妙恰在平衡为是,佳人伉丽得与华装之平,若华盛容体有过之,则装美而...
    柏小林阅读 482评论 0 1