Advertisements
Tinting images
The following code helps to get tinted image (UIImage) for a given image (UIImage). You can use the tintColor property in modern iOS UIImageView, UIButton and so on .
- (UIImage *)imageWithTint:(UIColor *)tintColor { // Begin drawing CGRect aRect = CGRectMake(0.f, 0.f, self.size.width, self.size.height); CGImageRef alphaMask; // // Compute mask flipping image // { UIGraphicsBeginImageContext(aRect.size); CGContextRef c = UIGraphicsGetCurrentContext(); // draw image CGContextTranslateCTM(c, 0, aRect.size.height); CGContextScaleCTM(c, 1.0, -1.0); [self drawInRect: aRect]; alphaMask = CGBitmapContextCreateImage(c); UIGraphicsEndImageContext(); } // UIGraphicsBeginImageContext(aRect.size); // Get the graphic context CGContextRef c = UIGraphicsGetCurrentContext(); // Draw the image [self drawInRect:aRect]; // Mask CGContextClipToMask(c, aRect, alphaMask); // Set the fill color space CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextSetFillColorSpace(c, colorSpace); // Set the fill color CGContextSetFillColorWithColor(c, tintColor.CGColor); UIRectFillUsingBlendMode(aRect, kCGBlendModeNormal); UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // Release memory CGColorSpaceRelease(colorSpace); CGImageRelease(alphaMask); return img; }
Tinting using tint property
UIImageView* imageView = [[UIImageView alloc]init]; UIImage* originalImage = [UIImage imageNamed:@"imageName"]; UIImage* imageForRendering = [originalImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; imageView.image = imageForRendering; imageView.tintColor = [UIColor redColor];