2016-08-01 49 views
0

我有一個代碼,其中根據條件是否爲true,翻轉圖像並更改其tintColor。無法更改翻轉的UIImage圖像的tintColor Swift 2 iOS

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

嘗試添加顏色爲你的形象用這種方法:

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) 
+0

謝謝。它適用於這個代碼!做一些非常簡單的事情似乎非常複雜。但爲什麼我的原始代碼中的「flippedImage」不能被視爲自己的UIImage,然後着色?我不明白爲什麼我的代碼不起作用。 –

+0

不知道爲什麼不工作tintColor。當與翻轉物體結合使用時,可能會有一種車。 –