Set Background Color on UIButton when Disabled? - ios

Is it possible to set the background color of a disabled UIButton? We'd like to use a more muted color when the button is disabled, but I do not see any methods within UIButton that would allow this. Is there a workaround or another way we could accomplish this?

I am concentrating on this comment of your's -"We'd like to use a more muted color when the button is disabled". If changing the alpha of the button is an acceptable solution you can very well use this code.
someButton.alpha = 0.5;//This code should be written in the place where the button is disabled.

The best way to work with button, in my honest opinion, is subclassing and customize UI, like in example:
class XYButton: UIButton {
override public var isEnabled: Bool {
didSet {
if self.isEnabled {
self.backgroundColor = self.backgroundColor?.withAlphaComponent(1.0)
} else {
self.backgroundColor = self.backgroundColor?.withAlphaComponent(0.5)
}
}
}
}
Then you can use XYButton either in your storyboards/xibs or programmatically.
** more elegant:
didSet {
self.backgroundColor = self.backgroundColor?.withAlphaComponent(isEnabled ? 1.0 : 0.5)
}

Seems that this is not possible as the background color property is controlled by the UIView class which is the parent of UIButton.
So UIButton control state doesn't own this property and doesn't control it.
But still you can inherit UIButton and overwrite the setEnabled method to update the color accordingly.
This is the most clear way to do it. as you can assign the inherited class to any UIButton in storyboard or Xib file. without the need for any connections. (no IBOutlets)
Hope this is helpful, if you wish I can share some code.

Hope this helps :
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 35)];
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[btn setBackgroundImage:image forState:UIControlStateDisabled];

This code is for Swift 2
let rect = CGRectMake(0, 0, someButton.frame.width,someButton.frame.height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColor(context, CGColorGetComponents(UIColor.lightGrayColor().CGColor))
CGContextFillRect(context, rect)
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0)
view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
someButton.setBackgroundImage(image, forState: .Disabled)
someButton.enabled = false

As suggested here:
https://stackoverflow.com/a/5725169/1586606 Set alpha property like;
myButton.alpha = 0.5

Related

iOS UIView subclass, draw see-through text to background

I want to draw text onto my subclass on UIView so that the text is cut out of the shape and the background behind the view shows through, just like in the OSX Mavericks logo found here.
I would say that I'm more of an intermediate/early advanced iOS developer so feel free to throw some crazy solutions at me. I'd expect I'd have to override drawRect in order to do this.
Thanks guys!
EDIT:
I should mention that my first attempt was making the text [UIColor clearColor] which didn't work since that just set the alpha component of the text to 0, which just showed the view through the text.
Disclaimer: I'm writing this without testing, so forgive me if I'm wrong here.
You should achieve what you need by these two steps:
Create a CATextLayer with the size of your view, set the backgroundColor to be fully transparent and foregroundColor to be opaque (by [UIColor colorWithWhite:0 alpha:1] and [UIColor colorWithWhite:0 alpha:0]. Then set the string property to the string you want to render, font and fontSize etc.
Set your view's layer's mask to this layer: myView.layer.mask = textLayer. You'll have to import QuartzCore to access the CALayer of your view.
Note that it's possible that I switched between the opaque and transparent color in the first step.
Edit: Indeed, Noah was right. To overcome this, I used CoreGraphics with the kCGBlendModeDestinationOut blend mode.
First, a sample view that shows that it indeed works:
#implementation TestView
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (void)drawRect:(CGRect)rect {
[[UIColor redColor] setFill];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:10];
[path fill];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context); {
CGContextSetBlendMode(context, kCGBlendModeDestinationOut);
[#"Hello!" drawAtPoint:CGPointZero withFont:[UIFont systemFontOfSize:24]];
} CGContextRestoreGState(context);
}
#end
After adding this to your view controller, you'll see the view behind TestView where Hello! is drawn.
Why does this work:
The blend mode is defined as R = D*(1 - Sa), meaning we need opposite alpha values than in the mask layer I suggested earlier. Therefore, all you need to do is to draw with an opaque color and this will be subtracted from the stuff you've drawn on the view beforehand.
If all you want is a white view with some stuff (text images, etc) cut out, then you can just do
yourView.layer.compositingFilter = "screenBlendMode"
This will leave the white parts white and the black parts will be see-through.
I actually figured out how to do it on my own surprisingly but #StatusReport's answer is completely valid and works as it stands now.
Here's how I did it:
-(void)drawRect:(CGRect)rect{
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor darkGrayColor]setFill]; //this becomes the color of the alpha mask
CGContextFillRect(context, rect);
CGContextSaveState(context);
[[UIColor whiteColor]setFill];
//Have to flip the context since core graphics is done in cartesian coordinates
CGContextTranslateCTM(context, 0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
[textToDraw drawInRect:rect withFont:[UIFont fontWithName:#"HelveticaNeue-Thin" size:40];
CGContextRestoreGState(context);
CGImageRef alphaMask = CGBitmapContextCreateImage(context);
[[UIColor whiteColor]setFill];
CGContextFillRect(context, rect);
CGContextSaveGState(context);
CGContentClipToMask(context, rect, alphaMask);
[backgroundImage drawInRect:rect];
CGContextRestoreGState(context);
CGImageRelease(alphaMask);
}
- (void)setTextToDraw:(NSString*)text{
if(text != textToDraw){
textToDraw = text;
[self setNeedsDisplay];
}
}
I have an #synthesize declaration for textToDraw so I could override the setter and call [self setNeedsDisplay]. Not sure if that's totally necessary or not.
I'm sure this has some typos but I can assure you, the spell checked version runs just fine.
StatusReport's accepted answer is beautifully written and because I have yet to find a Swift answer to this question, I thought I'd use his answer as the template for the Swift version. I added a little extensibility to the view by allowing the input of the string as a parameter of the view to remind people that that his can be done with all of the view's properties (corner radius, color, etc.) to make the view completely extensible.
The frame is zeroed out in the initializer because you're most likely going to apply constraints. If you aren't using constraints, omit this.
Swift 5
class CustomView: UIView {
var title: String
init(title: String) {
self.title = title
super.init(frame: CGRect.zero)
config()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func config() {
backgroundColor = UIColor.clear
}
override func draw(_ rect: CGRect) { // do not call super
UIColor.red.setFill()
let path = UIBezierPath(roundedRect: bounds, cornerRadius: 10)
path.fill()
weak var context = UIGraphicsGetCurrentContext() // Apple wants this to be weak
context?.saveGState()
context?.setBlendMode(CGBlendMode.destinationOut)
title.draw(at: CGPoint.zero, withAttributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 24)])
context?.restoreGState()
}
}
let customView = CustomView(title: "great success")

add border in CGRect iOS

I want to add a border in a CGRect. Although previous solutions suggest either this:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
CGContextFillRect(context, rectangle);
or something like this:
view.layer.borderWidth = 10;
view.layer.borderColor = [UIColor redColor].CGColor;
I cannot apply either of this in my approach.
In my mainView Controller I am having this code:
-(void)actionHint
{
CGRect viewRect = CGRectMake(kScreenWidth/2 -kMenuWidth, kScreenHeight/2-kMenuHeight - 70,kMenuWidth*10, kMenuHeight*4);
HintMenu* hintMenu = [HintMenu viewWithRect:viewRect];
[hintMenu.btnReveal addTarget:self action:#selector(actionReveal) forControlEvents:UIControlEventTouchUpInside];
[hintMenu.btnNewAnag addTarget:self action:#selector(actionNewAnagram) forControlEvents:UIControlEventTouchUpInside];
[self.gameView addSubview:hintMenu];
}
I am creating a game and I want a simple rect with some help actions to come on top of my current view. The code for viewRect is:
+(instancetype)viewWithRect:(CGRect)r
{
HintMenu* hint = [[HintMenu alloc] initWithFrame:r];
hint.userInteractionEnabled = YES;
UIImage* image=[UIImage imageNamed:#"btn"];
... rest of items in the cgrect
return hint;
}
Where should I add the code for adding the borders and what that code should be?
Your HintMenu is a type of view so in its initWithFrame method you can do:
self.layer.borderWidth = 10;
self.layer.borderColor = [UIColor redColor].CGColor;
You can use this code to create a bordered rectangle. All you have to do is import the QuartzCore framework. Feel free to copy+paste this code.
#import <QuartzCore/QuartzCore.h>
-(void)viewDidLoad{
//give it a blue background
self.layer.backgroundColor=[UIColor blueColor].CGColor;
//set the boarder width
self.layer.borderWidth=5;
//set the boarder color
self.layer.borderColor=[UIColor redColor].CGColor;
}

No Shadow/Emboss on UIBarButtonItem

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)

How do you change UIButton image alpha on disabled state?

I have a UIButton with an image and on its disabled state, this image should have .3 alpha.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *arrowImage = [UIImage imageNamed:#"arrow.png"];
[button setImage:arrowImage forState:UIControlStateNormal];
// The arrow should be half transparent here
[button setImage:arrowImage forState:UIControlStateDisabled];
How do I accomplish this?
UPDATE: I noticed, by default UIButton does reduce the alpha of the image on disabled state (probably at .5?). But I'd like to know how to fine-tune this value.
If setting alpha while the button is disabled doesn't work, then just make your disabled image at the alpha value you desire.
Just tested this, you can set the alpha on the UIButton, regardless of state and it works just fine.
self.yourButton.alpha = 0.25;
Credit goes to #bryanmac for his helpful answer. I used his code as a starting point, but found the same thing can be achieved without using a UIImageView.
Here's my solution:
- (UIImage *)translucentImageFromImage:(UIImage *)image withAlpha:(CGFloat)alpha
{
CGRect rect = CGRectZero;
rect.size = image.size;
UIGraphicsBeginImageContext(image.size);
[image drawInRect:rect blendMode:kCGBlendModeScreen alpha:alpha];
UIImage * translucentImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return translucentImage;
}
Set the button's background image for disabled state:
UIImage * disabledBgImage = [self translucentImageFromImage:originalBgImage withAlpha:0.5f];
[button setBackgroundImage:disabledBgImage forState:UIControlStateDisabled];
EDIT:
I refined my solution further by creating a category on UIImage with this method:
- (UIImage *)translucentImageWithAlpha:(CGFloat)alpha
{
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
[self drawInRect:bounds blendMode:kCGBlendModeScreen alpha:alpha];
UIImage * translucentImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return translucentImage;
}
Set the button's background image for disabled state:
UIImage * disabledBgImage = [originalBgImage translucentImageWithAlpha:0.5f];
[button setBackgroundImage:disabledBgImage forState:UIControlStateDisabled];
You need two instances of UIImage, one for enabled and one for disabled.
The tough part is for the disabled one, you can't set alpha on UIImage. You need to set it on UIImageView but button doesn't take an UIImageView, it takes a UIImage.
If you really want to do this, you can load the same image into the disabled button state after creating a resultant image from the UIImageView that has the alpha set on it.
UIImageView *uiv = [UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png"];
// get resultant UIImage from UIImageView
UIGraphicsBeginImageContext(uiv.image.size);
CGRect rect = CGRectMake(0, 0, uiv.image.size.width, uiv.image.size.height);
[uiv.image drawInRect:rect blendMode:kCGBlendModeScreen alpha:0.2];
UIImage *disabledArrow = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[button setImage:disabledArrow forState:UIControlStateDisabled];
That's a lot to go through to get an alpha controlled button image. There might be an easier way but that's all I could find. Hope that helps.
Subclassing UIButton and extending the setEnabled: method seems to work:
- (void) setEnabled:(BOOL)enabled {
[super setEnabled:enabled];
if (enabled) {
self.imageView.alpha = 1;
} else {
self.imageView.alpha = .25;
}
}
I haven't tested it thoroughly, but did find the value resets if the screen is rotated. Adding the same code to the setFrame: method fixes that, but I'm not sure if there are other situations where this value is changed.
In case anyone needs it, here's an answer in Swift:
Subclass UIButton and override enabled
class MyCustomButton: UIButton {
override var enabled: Bool {
didSet{
alpha = enabled ? 1.0 : 0.3
}
}
Set the class of any button you want to have this property to "MyCustomButton" (or whatever you choose to name it)
#IBOutlet weak var nextButton: MyCustomButton!
I found that none of these solutions really work. The cleanest way of doing it is to subclass, and instead of using self.imageView, just add your own custom imageView like this:
_customImageView = [[UIImageview alloc] initWithImage:image];
Then add your custom alpha like so:
- (void)setEnabled:(BOOL)enabled {
[super setEnabled:enabled];
if (enabled) {
_customImageView.alpha = 1.0f;
} else {
_customImageView.alpha = 0.25f;
}
}
Swift 3:
extension UIImage {
func copy(alpha: CGFloat) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: CGPoint.zero, blendMode: .normal, alpha: alpha)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
Usage:
button.setImage(image.copy(alpha: 0.3), for: .disabled)
The button’s image view. (read-only)
#property(nonatomic, readonly, retain) UIImageView *imageView
Although this property is read-only, its own properties are read/write.
A swift 4 version of Steph Sharp's answer:
extension UIImage {
func translucentImageWithAlpha(alpha: CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
let bounds = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
self.draw(in: bounds, blendMode: .screen, alpha: alpha)
let translucentImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return translucentImage!
}
}
Which you can use like this:
if let image = self.image(for: .normal) {
self.setImage(image.translucentImageWithAlpha(alpha: 0.3), for: .disabled)
}
- (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image; }
Use: [btnRegister setBackgroundImage:[self imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateDisabled];
btnRegister.enabled = false;
Here's a solution that extends the UIButton class. No need to sub-class. In my example, button alpha is set to 0.55 if .isEnabled is false, and 1.0 if it's true.
Swift 5:
extension UIButton {
override open var isEnabled: Bool {
didSet {
self.alpha = isEnabled ? 1.0 : 0.55
}
}
}

How would I tint an image programmatically on iOS?

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);

Resources