改变UIImage颜色 [英] Changing UIImage color

查看:175
本文介绍了改变UIImage颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图改变UIImage的颜色。我的代码:

I'm trying to change color of UIImage. My code:

-(UIImage *)coloredImage:(UIImage *)firstImage withColor:(UIColor *)color {
    UIGraphicsBeginImageContext(firstImage.size);

    CGContextRef context = UIGraphicsGetCurrentContext();
    [color setFill];

    CGContextTranslateCTM(context, 0, firstImage.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetBlendMode(context, kCGBlendModeCopy);
    CGRect rect = CGRectMake(0, 0, firstImage.size.width, firstImage.size.height);
    CGContextDrawImage(context, rect, firstImage.CGImage);

    CGContextClipToMask(context, rect, firstImage.CGImage);
    CGContextAddRect(context, rect);
    CGContextDrawPath(context,kCGPathElementMoveToPoint);

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

    return coloredImg;
}

此代码有效,但获得的图像并不是那么好:边界返回图像的像素是间歇性的,不像我的第一张图像那么平滑。我该如何解决这个问题?

This code works, but obtained image is not so well as shoud be: bounds pixels of returned image are intermittent and not so smooth as in my first image. How can I resolve this problem?

推荐答案

从iOS 7开始,这是最简单的方法。

Since iOS 7, this is the most simple way of doing it.

theImageView.image = [theImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[theImageView setTintColor:[UIColor redColor]];

在Swift 2.0+中

In Swift 2.0+

theImageView.image = theImageView.image?.imageWithRenderingMode(.AlwaysTemplate) 
theImageView.tintColor = UIColor.magentaColor()

在Swift 4.0及更高版本中

In Swift 4.0 and greater

theImageView.image = theImageView.image?.withRenderingMode(.AlwaysTemplate) 
theImageView.tintColor = .magenta

通过故事板

首先在您的资产中将图像配置为模板(在右侧栏上 - 渲染为)。然后图像的颜色将是应用的色调颜色。

First configure the image as template ( on right bar - Render as) in your assets. Then the color of the image would be the tint color applied.

这篇关于改变UIImage颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆