Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Left: system item, right: custom item

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.

like image 967
Chris Avatar asked Jun 18 '12 12:06

Chris


1 Answers

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;
}
like image 108
Alex-alex Avatar answered Oct 31 '22 00:10

Alex-alex