How to show tint colored image in CALayer on iOS?
Adding an answer based on J.Williams's answer - but updated for Swift 5, using a system image. Included all the layer setting up, etc. Hope this is useful! (Note: I think it's ridiculous that we can't just change the tint on an UIImage in a layer without jumping through a lot of crazy hoops like this)
let image = UIImage(systemName: "plus.circle.fill")
let circleLayer = CAShapeLayer()
let circleDiameter: CGFloat = 20.0
circleLayer.frame = CGRect(x: x - (circleDiameter / 2),
y: y - (circleDiameter / 2),
width: circleDiameter, height: circleDiameter)
let maskLayer = CALayer()
maskLayer.frame = circleLayer.bounds
maskLayer.contents = image?.cgImage
circleLayer.mask = maskLayer
circleLayer.backgroundColor = UIColor.systemPurple.cgColor
myView.layer.addSublayer(circleLayer)
I think my solution is far less cumbersome:
let maskLayer = CALayer()
maskLayer.frame = layer.bounds
maskLayer.contents = tintedImage.CGImage
layer.mask = maskLayer
layer.backgroundColor = UIColor.redColor().CGColor
let me know if it works fine:)
I guess that is possible on OSX using the filter property of CALayer, but in ios is not used. I think you should redraw the image totally, here is a sample code, it tints everything that has alpha > 0.
- (UIImage *)tintedImageWithColor:(UIColor *)tintColor blendingMode:(CGBlendMode)blendMode highQuality:(BOOL) yerOrNo;
{
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
if (yerOrNo) {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetShouldAntialias(context, true);
CGContextSetAllowsAntialiasing(context, true);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
}
[tintColor setFill];
CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
UIRectFill(bounds);
[self drawInRect:bounds blendMode:blendMode alpha:1.0f];
if (blendMode != kCGBlendModeDestinationIn)
[self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0];
UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return tintedImage;
}
I've found this snippet on the internet but I don't remember where.