小编典典

如何在iOS和WatchKit中更改图像tintColor

swift

我有一个名为“ theImageView”的UIImageView,其UIImage为单色
(透明背景),就像下面的左黑心一样。如何 按照iOS 7+导航栏图标中使用的着色方法
,在iOS 7或更高版本中以编程方式更改此图像的着色颜色

此方法也可以在Apple Watch应用程序的WatchKit中使用吗?


阅读 249

收藏
2020-07-07

共1个答案

小编典典

iOS对于iOS应用,在Swift 3、4或5中:

theImageView.image = theImageView.image?.withRenderingMode(.alwaysTemplate)
theImageView.tintColor = UIColor.red

For Swift 2:

theImageView.image = theImageView.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
theImageView.tintColor = UIColor.redColor()

Meanwhile, the modern Objective-C solution is:

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

Watchkit
在Apple Watch应用程序的WatchKit中,您可以设置模板图像的色调颜色。

您必须将图像添加到WatchKitApp的资产目录中,并在AttributesInspector中将图像集设置为呈现为模板图像。与iPhone应用程序不同,当前无法在WatchKit Extension中的代码中设置模板渲染。
设置要在应用程序的界面生成器中的WKInterfaceImage中使用的图像在WKInterfaceController中为名为“ theImage”的WKInterfaceImage创建一个IBOutlet…然后在Swift 3或4中设置色调颜色:

theImage.setTintColor(UIColor.red)

Swift 2:

theImage.setTintColor(UIColor.redColor())

To then set the tint color in Objective-C:

[self.theImage setTintColor:[UIColor redColor]];

如果您使用模板图像且未应用色调颜色,则将应用WatchKit应用程序的“全局色调”。如果您尚未设置全局色调,theImage则在用作模板图像时默认情况下将淡蓝色。

2020-07-07