我正在try 改变图像的 colored颜色 .我的代码:

-(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;
}

这段代码可以工作,但是获得的图像并不像应该的那样好:返回图像的边界像素是间歇性的,不像我的第一张图像那样平滑.我怎样才能解决这个问题呢?

推荐答案

自从iOS 7以来,这是最简单的方法.

Objective-C:

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

Swift 2.0:

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

Swift 4.0:

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

Storyboard:

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

Ios相关问答推荐

[NSJSONSerializationdataWithJSONObserver:选项:错误:]:SON写入中无效的顶级类型

在工作表上移动图像SwiftUI

SwiftUI绑定到特定的一个或多个枚举 case

自定义UIControl不适用于UITapGestureRecognizer

当操作修改查看条件时,按钮不重复

iOS应用程序冻结在UICollectionView代码,但我没有';没有任何UICollectionViews

为什么这个 init 被分派到一个内部扩展 init?

在 SwiftUI 中放置全局 NavigationPath 的位置

在标签中显示多个计数器但在同一屏幕(Swift,IOS)

以正确的方式在 Text() 中使用 colored颜色

Swift 5.7 - 使存在的任何协议符合 Hashable

在 Swift 中将 HTML 转换为纯文本

在原生和 phonegap 之间挣扎,简单的应用需求

如何将 iPhone OSStatus 代码转换为有用的东西?

什么是伞头?

呈现和关闭模态视图控制器

为所有 UIImageViews 添加圆角

CoreBluetooth 应用程序到底能在后台做什么?

如何立即移动 CALayer(无动画)

你如何以编程方式从视图控制器中画一条线?