我有一个代码,根据条件是否为真,翻转图像并更改其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。
如何让图像翻转并改变颜色?
答案 0 :(得分:0)
尝试使用此方法为图像添加颜色:
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)