Colored UIImage from grayscale imageЦветной UIImage из черно-белого изображения
For a very long time I couldn’t solve one problem that appeared time by time. Until it happened again a few day ago. But this time I decided that to put up with this state of affairs is not more possible and once again began to research. And the problem is the following. Assume you have a the monochrome image (for example, the icon of the stars for the Favorites button), and a skeleton application that implements the usage of skins (customization of the user interface). If one client wants the star to be red and another client wants it to be blue, the designer would have to repaint the image each time. But there must be an easier way to give a tint color using CoreGraphics functions.
Долгое время не мог подступиться к одной проблеме, которая то и дело периодически всплывала. В очередной раз я твердо решил, что мириться с таким положением дел не представляется более возможным и в очередной раз приступил к исследованиям. А проблема в следующем. Предположим, имеется в наличие монохромная картинка (например, иконка звезды для кнопки Избранные), а также некий каркас приложения, который реализует использование скинов (кастомизация пользовательского интерфейса). Если один клиент хочет, чтобы звезда была красной, а другой, чтобы синей, то дизайнеру придется каждый раз переделывать изображение. Но зачем, когда должно существовать более простой способ придать оттенок изображению с помощью графических функций CoreGraphics.
My goal was to apply this approach to the component of UIButton, but it is not hard to realize, there is is no difference for other components that worked with UIImage (for example, UIImageView). I’d just like to notice that the way I found after a long search, gave pixelated image output when run on a retina display. This was fixed by replacing the function UIGraphicsBeginImageContext UIGraphicsBeginImageContextWithOptionsTotal. Finally we have the following code::
- (UIImage *) imageByName:(NSString *)name withColor:(UIColor *)color {
// load the image
UIImage *img = = [UIImage imageWithContentsOfFile:name];
// begin a new image context, to draw our colored image onto
// UIGraphicsBeginImageContext(img.size);
UIGraphicsBeginImageContextWithOptions(img.size, NO, [UIScreen mainScreen].scale);
// get a reference to that context we created
CGContextRef context = UIGraphicsGetCurrentContext();
// set the fill color
[color setFill];
// translate/flip the graphics context (for transforming from CG* coords to UI* coords
CGContextTranslateCTM(context, 0, img.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, kCGBlendModeMultiply);
CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
CGContextDrawImage(context, rect, img.CGImage);
// set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
CGContextClipToMask(context, rect, img.CGImage);
CGContextAddRect(context, rect);
CGContextDrawPath(context,kCGPathFill);
// generate a new UIImage from the graphics context we drew onto
UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//return the color-burned image
return coloredImg;
}
У меня стояла задача применить все это дело к компоненту UIButton, но, как не сложно догадаться, принципиально это ничем не отличается по отношению к другим компонентам, работающим с объектами UIImage (например, UIImageView).
Сразу хочу заметить, что способ, который я нашел после долгих поисков, выдавал пиксилизированное изображение на выходе при запуске на ретина-дисплее. Это исправилось заменой функции UIGraphicsBeginImageContext на UIGraphicsBeginImageContextWithOptions
Итого имеем следующий код:
- (UIImage *) imageByName:(NSString *)name withColor:(UIColor *)color {
// load the image
UIImage *img = = [UIImage imageWithContentsOfFile:name];
// begin a new image context, to draw our colored image onto
// UIGraphicsBeginImageContext(img.size);
UIGraphicsBeginImageContextWithOptions(img.size, NO, [UIScreen mainScreen].scale);
// get a reference to that context we created
CGContextRef context = UIGraphicsGetCurrentContext();
// set the fill color
[color setFill];
// translate/flip the graphics context (for transforming from CG* coords to UI* coords
CGContextTranslateCTM(context, 0, img.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, kCGBlendModeMultiply);
CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
CGContextDrawImage(context, rect, img.CGImage);
// set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
CGContextClipToMask(context, rect, img.CGImage);
CGContextAddRect(context, rect);
CGContextDrawPath(context,kCGPathFill);
// generate a new UIImage from the graphics context we drew onto
UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//return the color-burned image
return coloredImg;
}
I have encountered the same problem as you, and you can share with your Demo for me? Thanks very much