0

I would like to change the color of an image that I have placed as a button in my navBar. The code I am using to create the image/button is:

UIImage *btnGoImage = [UIImage imageNamed:@"settings_cog.png"];
UIButton *btnGoPre = [UIButton buttonWithType:UIButtonTypeCustom];
btnGoPre.bounds = CGRectMake( 0, 0, 30, 30 );
[btnGoPre setImage:btnGoImage forState:UIControlStateNormal];

[btnGoPre addTarget:self action:@selector(loginAction) 
forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *btnGo = [[UIBarButtonItem alloc] initWithCustomView:btnGoPre];

If I wanted to change the image to red (it is currently gray). How would I do this? Thanks!

Stephane Delcroix
  • 16,134
  • 5
  • 57
  • 85
user2492064
  • 591
  • 1
  • 8
  • 21

2 Answers2

2

this is the method that will help to change the color of your image you need to pass the image and color as your input variables and it will return the output image

-(UIImage *)imageNamed:(NSString *)name withColor:(UIColor *)color 
{
    // load the image
    UIImage *img = [UIImage imageNamed:name];

    // begin a new image context, to draw our colored image onto
    UIGraphicsBeginImageContext(img.size);

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

    // set the blend mode to color burn, and the original image
    CGContextSetBlendMode(context, kCGBlendModeColorBurn);
    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;
}

and here is the example how you can call this method

yourImageView.image = [self imageNamed:@"yourImageName" withColor:[UIColor orangeColor]];
D-eptdeveloper
  • 2,430
  • 1
  • 16
  • 30
1

Try a UIBarButtonItem class tintColor property.

Bimawa
  • 3,535
  • 2
  • 25
  • 45