【问题标题】:Cannot change tintColor of a flipped UIImage image Swift 2 iOS无法更改翻转的 UIImage 图像 Swift 2 iOS 的 tintColor
【发布时间】:2023-04-03 10:17:02
【问题描述】:

我有一个代码,其中根据条件是否为真,翻转图像并更改其 tintColor。

func incoming(incoming: Bool) {
    let image = UIImage(named: "MessageBubble")?.imageWithRenderingMode(.AlwaysTemplate)
    var shownImage: UIImage
    // Check whether it is an incoming or outgoing message
    if incoming {

        let flippedImage = UIImage(CGImage: image!.CGImage!, scale: image!.scale, orientation: UIImageOrientation.UpMirrored)
        shownImage = flippedImage.imageWithRenderingMode(.AlwaysTemplate)
        bubbleImageView.tintColor = UIColor(red: 100/255, green: 200/255, blue: 100/255, alpha: 1)

    } else {

        shownImage = image!
        bubbleImageView.tintColor = UIColor(red: 100/255, green: 255/255, blue: 255/255, alpha: 1)


    }

    bubbleImageView.image = shownImage

}

但是,此代码不会翻转图像,但会正确应用 tintColor。如果删除了“.imageWithRenderingMode(.AlwaysTemplate)”函数,则图像正确翻转但不应用 tintColor。 (bubbleImageView 是一个 UIImageView)。

else 块下的代码以正确的 tintColor 显示。

如何让图像翻转并改变颜色?

【问题讨论】:

    标签: ios swift uiimageview uiimage


    【解决方案1】:

    尝试使用此方法为您的图像添加颜色:

    func coloredImage(image: UIImage, red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIImage! {
    
        let rect = CGRect(origin: CGPointZero, size: image.size)
    
        UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
    
        let context = UIGraphicsGetCurrentContext()
    
        image.drawInRect(rect)
    
    
        CGContextSetRGBFillColor(context, red, green, blue, alpha)
        CGContextSetBlendMode(context, CGBlendMode.SourceAtop)
    
        CGContextFillRect(context, rect)
    
        let result = UIGraphicsGetImageFromCurrentImageContext()
    
        UIGraphicsEndImageContext()
    
        return result
    
    
    }
    

    所以,在你的情况下,你应该这样做:

    let processedImage = coloredImage(bubbleImageView, red: 100/255, green: 255/255, blue: 255/255, alpha: 1)
    

    【讨论】:

    • 谢谢。它适用于此代码!做一些非常简单的事情似乎非常复杂。但是为什么我的原始代码中的“flippedImage”不能被视为它自己的 UIImage 然后着色呢?我不明白为什么我的代码不起作用。
    • 不知道为什么不工作 tintColor。与翻转的东西结合使用时,可能有点小车。
    猜你喜欢
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 2015-04-10
    • 2012-03-28
    • 2021-02-16
    • 2020-02-26
    • 1970-01-01
    相关资源
    最近更新 更多