Emil Adz Emil Adz - 6 months ago 28
Swift Question

How to color a white image in swift to another color?

I would like to color a white icon to another color in run time, I was trying to use the following method taken from here:

Masking an image in Swift using CALayer and UIImage

but without success:

func maskImageView() {
var maskImageSize = CGSizeMake(self.downloadImageView.frame.width, self.downloadImageView.frame.height)
UIGraphicsBeginImageContextWithOptions(maskImageSize, false, 0.0)

var color = UIColor(white: 1.0, alpha: 1.0)
color.setFill()

var rect = CGRectMake(0, 0, self.downloadImageView.frame.width, self.downloadImageView.frame.height)
UIRectFill(rect)

color = BrandColors.BRAND_FIRST_COLOR
color.setFill()

rect = CGRectMake((self.downloadImageView.frame.width/2)-100, (self.downloadImageView.frame.height/2)-100, 200, 200)
UIRectFill(rect)

var maskImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

var maskLayer = CALayer()
maskLayer.frame = CGRectMake(0, 0, self.downloadImageView.bounds.width, self.downloadImageView.bounds.height)
maskLayer.contents = maskImage.CGImage
maskLayer.contentsRect = CGRectMake(0, 0, self.downloadImageView.bounds.width, self.downloadImageView.bounds.height)
self.downloadImageView.layer.mask = maskLayer;
}


I can actually figure out how this masking thing works.
Can someone tell me what am I doing wrong?

Thanks in advance.

Answer

I was able to achieve this task with the following method:

func maskDownloadImageView() {
    downloadImageView.image = downloadImageView.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
    downloadImageView.tintColor = BrandColors.BRAND_FIRST_COLOR  
}

There is no need in using masking.