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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With