I have a UIToolbar with the alpha set to .6. Looks great - but it leaves the buttons with an alpha of .6 as well, which is okay but not really desirable. Is there some way to independently set the alpha of a UIBarButtonItem? How would I get these to look white instead of slightly grayed out?
When you set the alpha on a view, all subviews are composited with that same alpha value. What you can do instead of setting the alpha on the view itself is use a tint color or background color with an alpha value. This can produce similar effects, without causing all subviews to inherit the transparency.
toolbar.tintColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
If this doesn't work and you actually need to make the view itself transparent, you will have to rework your view hierarchy so that the opaque views are not subviews. Since bar button items aren't available as standard views, its probably not going to be workable in the toolbar case.
self.bottomToolbar.barStyle = UIBarStyleBlack;
self.bottomToolbar.translucent = YES;
self.bottomToolbar.backgroundColor = [UIColor clearColor];
View opacity set to 1 and these settings did it for me.
Above did not work for me in iOS 4.3, but this did:
Subclass UIToolbar, provide one method:
- (void)drawRect:(CGRect)rect
{
[[UIColor colorWithWhite:0 alpha:0.6f] set]; // or clearColor etc
CGContextFillRect(UIGraphicsGetCurrentContext(), rect);
}
I've found that barStyle does'n actually matter. Neither is setting background color to clear.
self.toolbar.barStyle = UIBarStyleDefault;
self.toolbar.tintColor = [UIColor colorWithWhite:0.0 alpha:0.5];
self.toolbar.translucent = YES;
Those lines done the job for me(ios4.3).
As I can understand, setting toolbars transfluent property to YES you've setting it to be with clear(transparent) background. Of course it depends on tint color you've set. If it doesn't contain alpha component the bar will be opaque.
The main issue with controlling the alpha value of the toolbar is that it applies to the entire toolbar and its buttons. If you set a backgroundColor with some alpha value < 1, the resulting colour is combined with the barStyle (UIBarStyleDefault or UIBarStyleBlack) which results in a more opaque colour than the original backgroundColor. If you set the barTintColor, it seems to override all other settings, including any alpha value you set, resulting in a completely opaque colour.
The only way I've been able to do reduce the alpha of the toolbar without affecting its buttons is by setting its background image via setBackgroundImage:forToolbarPosition:barMetrics:. You can create a 1px by 1px image with the desired colour and alpha:
+ (UIImage *)onePixelImageWithColor:(UIColor *)color {
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, 1, 1, 8, 0, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedFirst);
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
CGImageRef imgRef = CGBitmapContextCreateImage(context);
UIImage *image = [UIImage imageWithCGImage:imgRef];
CGImageRelease(imgRef);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return image;
}
[Swift version]
Then set the background Image:
[toolbar setBackgroundImage:[self onePixelImageWithColor:[[UIColor blackColor] colorWithAlphaComponent:0.7]]
forToolbarPosition:UIBarPositionBottom
barMetrics:UIBarMetricsDefault];
After many hours evaluating each methods above, I found only the method provided by Ryan H. is feasible. It is because this is the method you can manipulate the alpha value while others cannot.
Here is the version for Swift 3:
override func viewDidLoad() {
super.viewDidLoad()
let bgImageColor = UIColor.black.withAlphaComponent(0.6) //you can adjust the alpha value here
self.upperToolBar.setBackgroundImage(onePixelImageWithColor(color: bgImageColor),
forToolbarPosition: .any,
barMetrics: UIBarMetrics.default)
}
func onePixelImageWithColor(color : UIColor) -> UIImage {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
var context = CGContext(data: nil, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
context!.setFillColor(color.cgColor)
context!.fill(CGRect(x:0,y: 0, width: 1, height:1))
let image = UIImage(cgImage: context!.makeImage()!)
return image
}
Related
I would like to tint an image with a color reference. The results should look like the Multiply blending mode in Photoshop, where whites would be replaced with tint:
I will be changing the color value continuously.
Follow up: I would put the code to do this in my ImageView's drawRect: method, right?
As always, a code snippet would greatly aid in my understanding, as opposed to a link.
Update: Subclassing a UIImageView with the code Ramin suggested.
I put this in viewDidLoad: of my view controller:
[self.lena setImage:[UIImage imageNamed:kImageName]];
[self.lena setOverlayColor:[UIColor blueColor]];
[super viewDidLoad];
I see the image, but it is not being tinted. I also tried loading other images, setting the image in IB, and calling setNeedsDisplay: in my view controller.
Update: drawRect: is not being called.
Final update: I found an old project that had an imageView set up properly so I could test Ramin's code and it works like a charm!
Final, final update:
For those of you just learning about Core Graphics, here is the simplest thing that could possibly work.
In your subclassed UIView:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColor(context, CGColorGetComponents([UIColor colorWithRed:0.5 green:0.5 blue:0 alpha:1].CGColor)); // don't make color too saturated
CGContextFillRect(context, rect); // draw base
[[UIImage imageNamed:#"someImage.png"] drawInRect: rect blendMode:kCGBlendModeOverlay alpha:1.0]; // draw image
}
In iOS7, they've introduced tintColor property on UIImageView and renderingMode on UIImage. To tint an UIImage on iOS7, all you have to do is:
UIImageView* imageView = …
UIImage* originalImage = …
UIImage* imageForRendering = [originalImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
imageView.image = imageForRendering;
imageView.tintColor = [UIColor redColor]; // or any color you want to tint it with
First you'll want to subclass UIImageView and override the drawRect method. Your class needs a UIColor property (let's call it overlayColor) to hold the blend color and a custom setter that forces a redraw when the color changes. Something like this:
- (void) setOverlayColor:(UIColor *)newColor {
if (overlayColor)
[overlayColor release];
overlayColor = [newColor retain];
[self setNeedsDisplay]; // fires off drawRect each time color changes
}
In the drawRect method you'll want to draw the image first then overlay it with a rectangle filled with the color you want along with the proper blending mode, something like this:
- (void) drawRect:(CGRect)area
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
// Draw picture first
//
CGContextDrawImage(context, self.frame, self.image.CGImage);
// Blend mode could be any of CGBlendMode values. Now draw filled rectangle
// over top of image.
//
CGContextSetBlendMode (context, kCGBlendModeMultiply);
CGContextSetFillColor(context, CGColorGetComponents(self.overlayColor.CGColor));
CGContextFillRect (context, self.bounds);
CGContextRestoreGState(context);
}
Ordinarily to optimize the drawing you would restrict the actual drawing to only the area passed in to drawRect, but since the background image has to be redrawn each time the color changes it's likely the whole thing will need refreshing.
To use it create an instance of the object then set the image property (inherited from UIImageView) to the picture and overlayColor to a UIColor value (the blend levels can be adjusted by changing the alpha value of the color you pass down).
I wanted to tint an image with alpha and I created the following class. Please let me know if you find any problems with it.
I have named my class CSTintedImageView and it inherits from UIView since UIImageView does not call the drawRect: method, like mentioned in previous replies.
I have set a designated initializer similar to the one found in the UIImageView class.
Usage:
CSTintedImageView * imageView = [[CSTintedImageView alloc] initWithImage:[UIImage imageNamed:#"image"]];
imageView.tintColor = [UIColor redColor];
CSTintedImageView.h
#interface CSTintedImageView : UIView
#property (strong, nonatomic) UIImage * image;
#property (strong, nonatomic) UIColor * tintColor;
- (id)initWithImage:(UIImage *)image;
#end
CSTintedImageView.m
#import "CSTintedImageView.h"
#implementation CSTintedImageView
#synthesize image=_image;
#synthesize tintColor=_tintColor;
- (id)initWithImage:(UIImage *)image
{
self = [super initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
if(self)
{
self.image = image;
//set the view to opaque
self.opaque = NO;
}
return self;
}
- (void)setTintColor:(UIColor *)color
{
_tintColor = color;
//update every time the tint color is set
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
//resolve CG/iOS coordinate mismatch
CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, -rect.size.height);
//set the clipping area to the image
CGContextClipToMask(context, rect, _image.CGImage);
//set the fill color
CGContextSetFillColor(context, CGColorGetComponents(_tintColor.CGColor));
CGContextFillRect(context, rect);
//blend mode overlay
CGContextSetBlendMode(context, kCGBlendModeOverlay);
//draw the image
CGContextDrawImage(context, rect, _image.CGImage);
}
#end
Just a quick clarification (after some research on this topic). The Apple doc here clearly states that:
The UIImageView class is optimized to draw its images to the display. UIImageView does not call the drawRect: method of its subclasses. If your subclass needs to include custom drawing code, you should subclass the UIView class instead.
so don't even waste any time attempting to override that method in a UIImageView subclass. Start with UIView instead.
This could be very useful: PhotoshopFramework is one powerful library to manipulate images on Objective-C. This was developed to bring the same functionalities that Adobe Photoshop users are familiar. Examples: Set colors using RGB 0-255, apply blend filers, transformations...
Is open source, here is the project link: https://sourceforge.net/projects/photoshopframew/
UIImage * image = mySourceImage;
UIColor * color = [UIColor yellowColor];
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height) blendMode:kCGBlendModeNormal alpha:1];
UIBezierPath * path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, image.size.width, image.size.height)];
[color setFill];
[path fillWithBlendMode:kCGBlendModeMultiply alpha:1]; //look up blending modes for your needs
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//use newImage for something
For those of you who try to subclass an UIImageView class and get stuck at "drawRect: is not being called", note that you should subclass an UIView class instead, because for UIImageView classes, the "drawRect:" method is not called. Read more here: drawRect not being called in my subclass of UIImageView
Here is another way to implement image tinting, especially if you are already using QuartzCore for something else. This was my answer for a similar question.
Import QuartzCore:
#import <QuartzCore/QuartzCore.h>
Create transparent CALayer and add it as a sublayer for the image you want to tint:
CALayer *sublayer = [CALayer layer];
[sublayer setBackgroundColor:[UIColor whiteColor].CGColor];
[sublayer setOpacity:0.3];
[sublayer setFrame:toBeTintedImage.frame];
[toBeTintedImage.layer addSublayer:sublayer];
Add QuartzCore to your projects Framework list (if it isn't already there), otherwise you'll get compiler errors like this:
Undefined symbols for architecture i386: "_OBJC_CLASS_$_CALayer"
The only thing I can think of would be to create a rectangular mostly transparent view with the desired color and lay it over your image view by adding it as a subview. I'm not sure if this will really tint the image in the way you imagine though, I'm not sure how you would hack into an image and selectively replace certain colors with others... sounds pretty ambitious to me.
For example:
UIImageView *yourPicture = (however you grab the image);
UIView *colorBlock = [[UIView alloc] initWithFrame:yourPicture.frame];
//Replace R G B and A with values from 0 - 1 based on your color and transparency
colorBlock.backgroundColor = [UIColor colorWithRed:R green:G blue:B alpha:A];
[yourPicture addSubView:colorBlock];
Documentation for UIColor:
colorWithRed:green:blue:alpha:
Creates and returns a color object using the specified opacity and RGB component values.
+ (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha
Parameters
red - The red component of the color object, specified as a value from 0.0 to 1.0.
green - The green component of the color object, specified as a value from 0.0 to 1.0.
blue - The blue component of the color object, specified as a value from 0.0 to 1.0.
alpha - The opacity value of the color object, specified as a value from 0.0 to 1.0.
Return Value
The color object. The color information represented by this object is in the device RGB colorspace.
Also you might want to consider caching the composited image for performance and just rendering it in drawRect:, then updated it if a dirty flag is indeed dirty. While you might be changing it often, there may be cases where draws are coming in and you're not dirty, so you can simply refresh from the cache. If memory is more of an issue than performance, you can ignore this :)
I have a library I open-sourced for this: ios-image-filters
For Swift 2.0,
let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext()
imgView.image = imgView.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
imgView.tintColor = UIColor(red: 51/255.0, green: 51/255.0, blue:
51/255.0, alpha: 1.0)
I made macros for this purpose:
#define removeTint(view) \
if ([((NSNumber *)[view.layer valueForKey:#"__hasTint"]) boolValue]) {\
for (CALayer *layer in [view.layer sublayers]) {\
if ([((NSNumber *)[layer valueForKey:#"__isTintLayer"]) boolValue]) {\
[layer removeFromSuperlayer];\
break;\
}\
}\
}
#define setTint(view, tintColor) \
{\
if ([((NSNumber *)[view.layer valueForKey:#"__hasTint"]) boolValue]) {\
removeTint(view);\
}\
[view.layer setValue:#(YES) forKey:#"__hasTint"];\
CALayer *tintLayer = [CALayer new];\
tintLayer.frame = view.bounds;\
tintLayer.backgroundColor = [tintColor CGColor];\
[tintLayer setValue:#(YES) forKey:#"__isTintLayer"];\
[view.layer addSublayer:tintLayer];\
}
To use, simply just call:
setTint(yourView, yourUIColor);
//Note: include opacity of tint in your UIColor using the alpha channel (RGBA), e.g. [UIColor colorWithRed:0.5f green:0.0 blue:0.0 alpha:0.25f];
When removing the tint simply call:
removeTint(yourView);
I want to get the color of the background of a UILabel. I'm using this method:
- (UIColor *)colorOfPoint:(CGPoint)point{
unsigned char pixel[4] = {0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM(context, -point.x, -point.y);
[self.superview.layer renderInContext:context];
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
UIColor *color = [UIColor colorWithRed:pixel[0]/255.0
green:pixel[1]/255.0
blue:pixel[2]/255.0
alpha:pixel[3]/255.0];
return color;
}
However, when I call const CGFloat *componentColors = CGColorGetComponents([self colorOfPoint:self.amountLabel.frame.origin].CGColor); in a subview of UITableViewCell, it always return 0 (aka black) for the background. How could that be possible?
where are you running this code?
inside a subclass on UILabel?
I can't see why you call
[self.superView.layer renderInContext: ]
I suggest you change this to
[myLabel.layer renderInContext: ]
where myLabel is the pointer to the label you want the colour from.
Incidentally, have you tried myLabel.backgroundColor ?
(the backgroundColor property is read/write, i.e. there is a getter there as well as a setter..) the code you have for getting a colour from a specific point is good, but it seems overkill for a label, better suited to an image or something, unless you've filled it with a gradient or a pattern image this seems like a pretty expensive way to get the background colour..
I've got a problem with an custom UIBarButtonItem. When I create an custom UIBarButtonItem via
[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:#"FilterIcon.png"] style:UIBarButtonItemStyleBordered target:self action:#selector(filterTouched:)];
the resulting button does not have the "embossed" look, that the system items achieve by placing a semi-transparent black shadow behind their icons.
On the left you see the "Organize" system bar button item, rightthe result of the code from above.
Creating the shadow in the resource is futile, because iOS/Cocoa only used the mask of the image and discards any color information.
Interestingly, if I create the bar button item in the Interface-Builder it looks fine. However, in the context of my problem, I need to create the button item in code.
There is Objective-C version of James Furey's script.
- (UIImage *)applyToolbarButtonStyling:(UIImage *)oldImage {
float shadowOffset = 1;
float shadowOpacity = .54;
CGRect imageRect = CGRectMake(0, 0, oldImage.size.width, oldImage.size.height);
CGRect shadowRect = CGRectMake(0, shadowOffset, oldImage.size.width, oldImage.size.height);
CGRect newRect = CGRectUnion(imageRect, shadowRect);
UIGraphicsBeginImageContextWithOptions(newRect.size, NO, oldImage.scale);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -(newRect.size.height));
CGContextSaveGState(ctx);
CGContextClipToMask(ctx, shadowRect, oldImage.CGImage);
CGContextSetFillColorWithColor(ctx, [UIColor colorWithWhite:0 alpha:shadowOpacity].CGColor);
CGContextFillRect(ctx, shadowRect);
CGContextRestoreGState(ctx);
CGContextClipToMask(ctx, imageRect, oldImage.CGImage);
CGContextSetFillColorWithColor(ctx, [UIColor colorWithWhite:1 alpha:1].CGColor);
CGContextFillRect(ctx, imageRect);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
I think the reason this occurs is covered by these answers to another question:
https://stackoverflow.com/a/3476424/1210490
https://stackoverflow.com/a/6528603/1210490
UIBarButtonItems behave differently depending on where you programmatically attach them. If you attach them to a toolbar, they'll become white "embossed" icons. If you attach them to a navigation bar, they won't.
I've spent the last few hours writing a function to apply toolbar UIBarButtonItem styling to UIImages. It's written in C# for MonoTouch, but I'm sure you'll be able to tweak it to Obj-C no problemo...
UIImage ApplyToolbarButtonStyling(UIImage oldImage)
{
float shadowOffset = 1f;
float shadowOpacity = .54f;
RectangleF imageRect = new RectangleF(PointF.Empty, oldImage.Size);
RectangleF shadowRect = new RectangleF(new PointF(0, shadowOffset), oldImage.Size);
RectangleF newRect = RectangleF.Union(imageRect, shadowRect);
UIGraphics.BeginImageContextWithOptions(newRect.Size, false, oldImage.CurrentScale);
CGContext ctxt = UIGraphics.GetCurrentContext();
ctxt.ScaleCTM(1f, -1f);
ctxt.TranslateCTM(0, -newRect.Size.Height);
ctxt.SaveState();
ctxt.ClipToMask(shadowRect, oldImage.CGImage);
ctxt.SetFillColor(UIColor.FromWhiteAlpha(0f, shadowOpacity).CGColor);
ctxt.FillRect(shadowRect);
ctxt.RestoreState();
ctxt.ClipToMask(imageRect, oldImage.CGImage);
ctxt.SetFillColor(UIColor.FromWhiteAlpha(1f, 1f).CGColor);
ctxt.FillRect(imageRect);
UIImage newImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return newImage;
}
So, a UIBarButtonItem that used to look like this:
Created instead with the function above, like this:
UIBarButtonItem barButtonItem = new UIBarButtonItem(ApplyToolbarButtonStyling(UIImage.FromFile("MusicIcon.png")), UIBarButtonItemStyle.Plain, delegate {});
Would now look like this:
Hope this helps someone in the future.
Take note of the shadow offset in James Furey's script.
I've made the following experience:
float shadowOffset = 1.0f // for a UIBarButtonItem in UINavigationItem
float shadowOffset = 0.0f // for a UIBarButtonItem in UIToolBar
This was observed with iOS 6.1 SDK.
(Now obsolete under iOS 7)
I'm trying to modify some simple "create a paint app" code to have a white background colour, rather than the black that it is set to. The example code is located at:
http://blog.effectiveui.com/?p=8105
I've tried setting self.backgroundcolor = [UIColor whiteColor], also [[UIColor whiteColor] setFill] with no effect. I'm missing something very basic due to my inexperience.
Does anyone have any ideas? Many thanks in advance!
I've added a couple of lines to the drawRect that should do it for you. You were on the right track, but when you set the color to white, you actually need to then fill the paintView rectangle with it:
- (void)drawRect:(CGRect)rect {
if(touch != nil){
CGContextRef context = UIGraphicsGetCurrentContext();
//clear background color to white
[[UIColor whiteColor] setFill];
CGContextFillRect(context, rect);
hue += 0.005;
if(hue > 1.0) hue = 0.0;
UIColor *color = [UIColor colorWithHue:hue saturation:0.7 brightness:1.0 alpha:1.0];
CGContextSetStrokeColorWithColor(context, [color CGColor]);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, 15);
CGPoint lastPoint = [touch previousLocationInView:self];
CGPoint newPoint = [touch locationInView:self];
CGContextMoveToPoint(context, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(context, newPoint.x, newPoint.y);
CGContextStrokePath(context);
}
}
The reason view.backgroundColor = [UIColor whiteColor]; didn't work is that any view that implements drawRect ignores the backgroundColor property, and the programmer is responsible for drawing the whole view contents, including the background.
I think the part you've missed is this section of PaintView:
- (BOOL) initContext:(CGSize)size {
int bitmapByteCount;
int bitmapBytesPerRow;
// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = (size.width * 4);
bitmapByteCount = (bitmapBytesPerRow * size.height);
// Allocate memory for image data. This is the destination in memory
// where any drawing to the bitmap context will be rendered.
cacheBitmap = malloc( bitmapByteCount );
if (cacheBitmap == NULL){
return NO;
}
cacheContext = CGBitmapContextCreate (cacheBitmap, size.width, size.height, 8, bitmapBytesPerRow, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst);
return YES;
}
That creates a single context, which it calls a cache, that all subsequent touches are drawn to. In the view's drawRect: it simply copies the cache to the output.
One of the flags it provides — kCGImageAlphaNoneSkipFirst — specifies that the cached context has no alpha channel. So when it's drawn there's no chance for the background to show through regardless of any other factor; the black comes from the cacheContext just as if you'd painted black with your finger.
So what you really want to do is to fill the cacheContext with white before you begin. You can either do that by memsetting the cacheBitmap array, since you've explicitly told the context where to store its data, or you can use a suitable CGContextFillRect to the cacheContext.
If you want to use the source code but have a clear background to the image you are creating and 'inking' on - when you setup the cachedBitmap, do it like this.
cacheContext = CGBitmapContextCreate ( cacheBitmap
, size.width
, size.height
, 8
, bitmapBytesPerRow
, CGColorSpaceCreateDeviceRGB()
, kCGImageAlphaPremultipliedFirst
);
That way, when you set your stroke color for the 'ink' only the 'ink' will be painted. Ensure that the drawing View also has a background color of clearColor, and opaque set to NO.
This means that the view that the drawing view has been added to will now be visible underneath or through this drawing view. Therefore set the background color of that view to whatever you want or alternatively, put a UIImageView behind the drawing view and voila! You can insert an image for lined paper or graph paper or whatever you want!
I would like to tint an image with a color reference. The results should look like the Multiply blending mode in Photoshop, where whites would be replaced with tint:
I will be changing the color value continuously.
Follow up: I would put the code to do this in my ImageView's drawRect: method, right?
As always, a code snippet would greatly aid in my understanding, as opposed to a link.
Update: Subclassing a UIImageView with the code Ramin suggested.
I put this in viewDidLoad: of my view controller:
[self.lena setImage:[UIImage imageNamed:kImageName]];
[self.lena setOverlayColor:[UIColor blueColor]];
[super viewDidLoad];
I see the image, but it is not being tinted. I also tried loading other images, setting the image in IB, and calling setNeedsDisplay: in my view controller.
Update: drawRect: is not being called.
Final update: I found an old project that had an imageView set up properly so I could test Ramin's code and it works like a charm!
Final, final update:
For those of you just learning about Core Graphics, here is the simplest thing that could possibly work.
In your subclassed UIView:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColor(context, CGColorGetComponents([UIColor colorWithRed:0.5 green:0.5 blue:0 alpha:1].CGColor)); // don't make color too saturated
CGContextFillRect(context, rect); // draw base
[[UIImage imageNamed:#"someImage.png"] drawInRect: rect blendMode:kCGBlendModeOverlay alpha:1.0]; // draw image
}
In iOS7, they've introduced tintColor property on UIImageView and renderingMode on UIImage. To tint an UIImage on iOS7, all you have to do is:
UIImageView* imageView = …
UIImage* originalImage = …
UIImage* imageForRendering = [originalImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
imageView.image = imageForRendering;
imageView.tintColor = [UIColor redColor]; // or any color you want to tint it with
First you'll want to subclass UIImageView and override the drawRect method. Your class needs a UIColor property (let's call it overlayColor) to hold the blend color and a custom setter that forces a redraw when the color changes. Something like this:
- (void) setOverlayColor:(UIColor *)newColor {
if (overlayColor)
[overlayColor release];
overlayColor = [newColor retain];
[self setNeedsDisplay]; // fires off drawRect each time color changes
}
In the drawRect method you'll want to draw the image first then overlay it with a rectangle filled with the color you want along with the proper blending mode, something like this:
- (void) drawRect:(CGRect)area
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
// Draw picture first
//
CGContextDrawImage(context, self.frame, self.image.CGImage);
// Blend mode could be any of CGBlendMode values. Now draw filled rectangle
// over top of image.
//
CGContextSetBlendMode (context, kCGBlendModeMultiply);
CGContextSetFillColor(context, CGColorGetComponents(self.overlayColor.CGColor));
CGContextFillRect (context, self.bounds);
CGContextRestoreGState(context);
}
Ordinarily to optimize the drawing you would restrict the actual drawing to only the area passed in to drawRect, but since the background image has to be redrawn each time the color changes it's likely the whole thing will need refreshing.
To use it create an instance of the object then set the image property (inherited from UIImageView) to the picture and overlayColor to a UIColor value (the blend levels can be adjusted by changing the alpha value of the color you pass down).
I wanted to tint an image with alpha and I created the following class. Please let me know if you find any problems with it.
I have named my class CSTintedImageView and it inherits from UIView since UIImageView does not call the drawRect: method, like mentioned in previous replies.
I have set a designated initializer similar to the one found in the UIImageView class.
Usage:
CSTintedImageView * imageView = [[CSTintedImageView alloc] initWithImage:[UIImage imageNamed:#"image"]];
imageView.tintColor = [UIColor redColor];
CSTintedImageView.h
#interface CSTintedImageView : UIView
#property (strong, nonatomic) UIImage * image;
#property (strong, nonatomic) UIColor * tintColor;
- (id)initWithImage:(UIImage *)image;
#end
CSTintedImageView.m
#import "CSTintedImageView.h"
#implementation CSTintedImageView
#synthesize image=_image;
#synthesize tintColor=_tintColor;
- (id)initWithImage:(UIImage *)image
{
self = [super initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
if(self)
{
self.image = image;
//set the view to opaque
self.opaque = NO;
}
return self;
}
- (void)setTintColor:(UIColor *)color
{
_tintColor = color;
//update every time the tint color is set
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
//resolve CG/iOS coordinate mismatch
CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, -rect.size.height);
//set the clipping area to the image
CGContextClipToMask(context, rect, _image.CGImage);
//set the fill color
CGContextSetFillColor(context, CGColorGetComponents(_tintColor.CGColor));
CGContextFillRect(context, rect);
//blend mode overlay
CGContextSetBlendMode(context, kCGBlendModeOverlay);
//draw the image
CGContextDrawImage(context, rect, _image.CGImage);
}
#end
Just a quick clarification (after some research on this topic). The Apple doc here clearly states that:
The UIImageView class is optimized to draw its images to the display. UIImageView does not call the drawRect: method of its subclasses. If your subclass needs to include custom drawing code, you should subclass the UIView class instead.
so don't even waste any time attempting to override that method in a UIImageView subclass. Start with UIView instead.
This could be very useful: PhotoshopFramework is one powerful library to manipulate images on Objective-C. This was developed to bring the same functionalities that Adobe Photoshop users are familiar. Examples: Set colors using RGB 0-255, apply blend filers, transformations...
Is open source, here is the project link: https://sourceforge.net/projects/photoshopframew/
UIImage * image = mySourceImage;
UIColor * color = [UIColor yellowColor];
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height) blendMode:kCGBlendModeNormal alpha:1];
UIBezierPath * path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, image.size.width, image.size.height)];
[color setFill];
[path fillWithBlendMode:kCGBlendModeMultiply alpha:1]; //look up blending modes for your needs
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//use newImage for something
For those of you who try to subclass an UIImageView class and get stuck at "drawRect: is not being called", note that you should subclass an UIView class instead, because for UIImageView classes, the "drawRect:" method is not called. Read more here: drawRect not being called in my subclass of UIImageView
Here is another way to implement image tinting, especially if you are already using QuartzCore for something else. This was my answer for a similar question.
Import QuartzCore:
#import <QuartzCore/QuartzCore.h>
Create transparent CALayer and add it as a sublayer for the image you want to tint:
CALayer *sublayer = [CALayer layer];
[sublayer setBackgroundColor:[UIColor whiteColor].CGColor];
[sublayer setOpacity:0.3];
[sublayer setFrame:toBeTintedImage.frame];
[toBeTintedImage.layer addSublayer:sublayer];
Add QuartzCore to your projects Framework list (if it isn't already there), otherwise you'll get compiler errors like this:
Undefined symbols for architecture i386: "_OBJC_CLASS_$_CALayer"
The only thing I can think of would be to create a rectangular mostly transparent view with the desired color and lay it over your image view by adding it as a subview. I'm not sure if this will really tint the image in the way you imagine though, I'm not sure how you would hack into an image and selectively replace certain colors with others... sounds pretty ambitious to me.
For example:
UIImageView *yourPicture = (however you grab the image);
UIView *colorBlock = [[UIView alloc] initWithFrame:yourPicture.frame];
//Replace R G B and A with values from 0 - 1 based on your color and transparency
colorBlock.backgroundColor = [UIColor colorWithRed:R green:G blue:B alpha:A];
[yourPicture addSubView:colorBlock];
Documentation for UIColor:
colorWithRed:green:blue:alpha:
Creates and returns a color object using the specified opacity and RGB component values.
+ (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha
Parameters
red - The red component of the color object, specified as a value from 0.0 to 1.0.
green - The green component of the color object, specified as a value from 0.0 to 1.0.
blue - The blue component of the color object, specified as a value from 0.0 to 1.0.
alpha - The opacity value of the color object, specified as a value from 0.0 to 1.0.
Return Value
The color object. The color information represented by this object is in the device RGB colorspace.
Also you might want to consider caching the composited image for performance and just rendering it in drawRect:, then updated it if a dirty flag is indeed dirty. While you might be changing it often, there may be cases where draws are coming in and you're not dirty, so you can simply refresh from the cache. If memory is more of an issue than performance, you can ignore this :)
I have a library I open-sourced for this: ios-image-filters
For Swift 2.0,
let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext()
imgView.image = imgView.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
imgView.tintColor = UIColor(red: 51/255.0, green: 51/255.0, blue:
51/255.0, alpha: 1.0)
I made macros for this purpose:
#define removeTint(view) \
if ([((NSNumber *)[view.layer valueForKey:#"__hasTint"]) boolValue]) {\
for (CALayer *layer in [view.layer sublayers]) {\
if ([((NSNumber *)[layer valueForKey:#"__isTintLayer"]) boolValue]) {\
[layer removeFromSuperlayer];\
break;\
}\
}\
}
#define setTint(view, tintColor) \
{\
if ([((NSNumber *)[view.layer valueForKey:#"__hasTint"]) boolValue]) {\
removeTint(view);\
}\
[view.layer setValue:#(YES) forKey:#"__hasTint"];\
CALayer *tintLayer = [CALayer new];\
tintLayer.frame = view.bounds;\
tintLayer.backgroundColor = [tintColor CGColor];\
[tintLayer setValue:#(YES) forKey:#"__isTintLayer"];\
[view.layer addSublayer:tintLayer];\
}
To use, simply just call:
setTint(yourView, yourUIColor);
//Note: include opacity of tint in your UIColor using the alpha channel (RGBA), e.g. [UIColor colorWithRed:0.5f green:0.0 blue:0.0 alpha:0.25f];
When removing the tint simply call:
removeTint(yourView);