Sam Win
Sam Win

Reputation: 1

Cannot change tintColor of a flipped UIImage image Swift 2 iOS

I have a code where, depending on whether a condition is true, an image is flipped and its tintColor changed.

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

}

However, this code does not flip the image but it is correctly applying the tintColor. If the ".imageWithRenderingMode(.AlwaysTemplate)" function is removed, the image is correctly flipped but the tintColor is not applied. (bubbleImageView is a UIImageView).

The code under else block shows up with the correct tintColor.

How can I get both the image flipped and its color changed?

Upvotes: 0

Views: 411

Answers (1)

Anton Novoselov
Anton Novoselov

Reputation: 769

Try to add color for your images with this method:

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


}

So, in your case, you should do:

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

Upvotes: 1

Related Questions