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

发布于 2021-01-31 23:56:56

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


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

关注者
0
被浏览
300
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。

    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则在用作模板图像时默认情况下将淡蓝色。



推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看