I want not to change the backgroundColor of an UIImage,
but rather to change the color of the whole image.
Because I have got standard forms which I can move fr
For swift 3.2 and 4
extension UIImageView{
func changePngColorTo(color: UIColor){
guard let image = self.image else {return}
self.image = image.withRenderingMode(.alwaysTemplate)
self.tintColor = color
}
}
Use :
self.yourImageView.changePngColorTo(color: .red)
UIImage *image = [UIImage imageNamed:@"triangle.png"];
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClipToMask(context, rect, image.CGImage);
CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImage *flippedImage = [UIImage imageWithCGImage:img.CGImage
scale:1.0 orientation: UIImageOrientationDownMirrored];
yourUIImageView.image = flippedImage;
Swift + Interface builder (storyboard)
If you added the UIImageView in the interface builder:
myIcon.image = myIcon.image!.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
myIcon.tintColor = UIColor.red // your color
where myIcon
is an outlet from your storyboard, ex: @IBOutlet weak var myIcon: UIImageView!
Change the color of the image in UIImageView:
public extension UIImageView {
func tintImage(color: UIColor) {
image = image?.tint(color: color)
}
}
Just call the method:
imageView.tintImage(color: .red)
The accepted answer is correct, but there is a much more easy way for UIImageView
:
Obj-C:
UIImage *image = [UIImage imageNamed:@"foo.png"];
theImageView.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[theImageView setTintColor:[UIColor redColor]];
Swift 2:
let theImageView = UIImageView(image: UIImage(named:"foo")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate))
theImageView.tintColor = UIColor.redColor()
Swift 3:
let theImageView = UIImageView(image: UIImage(named:"foo")!.withRenderingMode(.alwaysTemplate))
theImageView.tintColor = UIColor.red
You can also do this in swift with the following code:
// language: Swift
let tintedImage = UIImageView(image: UIImage(named:"whatever")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate))
tintedImage.tintColor = UIColor.redColor()