颜色色调 UIButton 图像

Color Tint UIButton Image(颜色色调 UIButton 图像)

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

问题描述

我注意到,当我将白色或黑色 UIImage 放入 UISegmentedControl 时,它会自动对其进行颜色遮罩以匹配分段控件的色调.我认为这真的很酷,并且想知道我是否也可以在其他地方这样做.例如,我有一堆形状统一但颜色多样的按钮.除了为每个按钮制作一个 PNG 之外,我是否可以以某种方式使用这种颜色遮罩为所有按钮使用相同的图像,然后设置一个色调颜色或其他东西来改变它们的实际颜色?

I noticed that when I place a white or black UIImage into a UISegmentedControl it automatically color masks it to match the tint of the segmented control. I thought this was really cool, and was wondering if I could do this elsewhere as well. For example, I have a bunch of buttons that have a uniform shape but varied colors. Instead of making a PNG for each button, could I somehow use this color masking to use the same image for all of them but then set a tint color or something to change their actual color?

推荐答案

从 iOS 7 开始,UIImage 上有一个新方法来指定渲染模式.使用渲染模式 UIImageRenderingModeAlwaysTemplate 将允许图像颜色由按钮的色调颜色控制.

As of iOS 7, there is a new method on UIImage to specify the rendering mode. Using the rendering mode UIImageRenderingModeAlwaysTemplate will allow the image color to be controlled by the button's tint color.

目标-C

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [[UIImage imageNamed:@"image_name"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[button setImage:image forState:UIControlStateNormal]; 
button.tintColor = [UIColor redColor];

斯威夫特

let button = UIButton(type: .custom)
let image = UIImage(named: "image_name")?.withRenderingMode(.alwaysTemplate)
button.setImage(image, for: .normal)
button.tintColor = UIColor.red

这篇关于颜色色调 UIButton 图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:颜色色调 UIButton 图像

基础教程推荐