iOS中的抗锯齿自定义栏按钮图像

时间:2013-07-14 00:37:47

标签: ios cocoa-touch custom-controls uibarbuttonitem antialiasing

我正在尝试使用自定义栏按钮图像。我创建了一个简单的PNG图像,其中包含白色物体和透明背景recommended by Apple

enter image description here

如您所见,没有应用抗锯齿(这是我的确切图像,像素的像素)。

Apple确实建议使用消除锯齿,但不提供任何更多细节。我原以为这将是软件的功能,就像文本一样,而不是预先应用于图像。

问题是 - 如何以编程方式为我的自定义栏按钮图像提供抗锯齿?

我尝试了几件事,但没有任何事情可以帮我。这是我尝试过的一件事:

- (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;
}

然后我像这样创建我的分段控件:

- (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];
}

提前谢谢!

1 个答案:

答案 0 :(得分:1)

IOS不会为渲染图像添加抗锯齿 - 只能从代码中提取项目。在保存到文件之前,您必须对图像进行反锯齿处理。

从代码中反对别名图像的方法是绘制代码。