色彩UIButton图像 [英] Color Tint UIButton Image
问题描述
我注意到,当我放置白色或黑色的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];
Swift
let button = UIButton(type: .custom)
let image = UIImage(named: "image_name")?.withRenderingMode(.alwaysTemplate)
button.setImage(image, for: .normal)
button.tintColor = UIColor.red
这篇关于色彩UIButton图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!