I'm trying to use a custom bar button image. I've created a simple PNG image with a white object and a transparent background as recommended by Apple:
As you can see, there is no anti-aliasing being applied (that is my exact image, pixel for pixel).
Apple does recommend to use Anti-aliasing, but don't provide any more detail. I would have thought this would be a function of the software like it would with text, rather than pre-applying it to the image.
The question is--how can I programatically provide anti-aliasing for my custom bar button images?
I have tried several things but nothing is doing it for me. Here's one thing I tried:
- (UIImage *)antialiasedImage
{
// Check to see if Antialiased Image has already been initialized
if (_antialiasedImage != nil) {
return _antialiasedImage;
}
// Get Device Scale
CGFloat scale = [[UIScreen mainScreen] scale];
// Get the Image from Resource
UIImage *buttonImage = [UIImage imageNamed:@"ReferenceFieldIcon"]; // .png???
// Get the CGImage from UIImage
CGImageRef imageRef = [buttonImage CGImage];
// Find width and height
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
// Begin Context
UIGraphicsBeginImageContextWithOptions(buttonImage.size, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Set Antialiasing Parameters
CGContextSetAllowsAntialiasing(context, YES);
CGContextSetShouldAntialias(context, YES);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
// Draw Image Ref on Context
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
// End Context
UIGraphicsEndImageContext();
// Set CGImage to UIImage
_antialiasedImage =
[UIImage imageWithCGImage:imageRef scale:scale orientation:UIImageOrientationUp];
// Release Image Ref
CGImageRelease(imageRef);
return _antialiasedImage;
}
Then I create my Segmented Control Like So:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSArray *centerItemsArray =
[NSArray arrayWithObjects: @"S",
self.antialiasedImage,
@"D",
nil];
UISegmentedControl *centerSegCtrl =
[[UISegmentedControl alloc] initWithItems:centerItemsArray];
centerSegCtrl.segmentedControlStyle = UISegmentedControlStyleBar;
UIBarButtonItem *centerButtonItem =
[[UIBarButtonItem alloc] initWithCustomView:(UIView *)centerSegCtrl];
UIBarButtonItem *flexibleSpace =
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil];
NSArray *barArray = [NSArray arrayWithObjects: flexibleSpace,
centerButtonItem,
flexibleSpace,
nil];
[self setToolbarItems:barArray];
}
Thank you in advance!
IOS doesn't add anti-aliasing to rendered images--only items drawn from code. You'll have to anti-alias the image before saving to file.
The way to anti-alias images from code is to draw them code.