[英]Cannot change tintColor of a flipped UIImage image Swift 2 iOS
我有一個代碼,其中根據條件是否為真,翻轉圖像並更改其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。
如何同時翻轉圖像和改變顏色?
嘗試使用此方法為圖像添加顏色:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.