如何在 iOS 和 WatchKit 中更改图像 tintColor [英] How can I change image tintColor in iOS and WatchKit

查看:32
本文介绍了如何在 iOS 和 WatchKit 中更改图像 tintColor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an UIImageView called "theImageView", with UIImage in a single color (transparent background) just like the left black heart below. How can I change the tint color of this image programmatically in iOS 7 or above, as per the tint method used in the iOS 7+ Navigation Bar icons?

此方法是否也适用于 Apple Watch 应用的 WatchKit?

Can this method also work in WatchKit for an Apple Watch app?

推荐答案

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

iOS
For an iOS app, in Swift 3, 4 or 5:

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

对于 Swift 2:

For Swift 2:

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

与此同时,现代的 Objective-C 解决方案是:

Meanwhile, the modern Objective-C solution is:

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

<小时>

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

  1. 您必须将图像添加到 WatchKit 应用程序中的资产目录,并将图像集设置为在属性检查器中呈现为模板图像.与 iPhone 应用不同,目前您无法在 WatchKit 扩展中的代码中设置模板渲染.
  2. 在应用的界面构建器中设置要在 WKInterfaceImage 中使用的图像
  3. 在 WKInterfaceController 中为名为theImage"的 WKInterfaceImage 创建一个 IBOutlet...

然后在 Swift 3 或 4 中设置色调颜色:

To then set the tint color in Swift 3 or 4:

theImage.setTintColor(UIColor.red)

斯威夫特 2:

theImage.setTintColor(UIColor.redColor())

然后在 Objective-C 中设置色调颜色:

To then set the tint color in Objective-C:

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

如果您使用模板图像并且不应用色调颜色,则将应用 WatchKit 应用的全局色调.如果您没有设置全局色调,theImage 在用作模板图像时默认会被染成淡蓝色.

If you use a template image and do not apply a tint colour, the Global Tint for your WatchKit app will be applied. If you have not set a Global Tint, theImage will be tinted light blue by default when used as a template image.

这篇关于如何在 iOS 和 WatchKit 中更改图像 tintColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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