1

我正在尝试使用自定义栏按钮图像。我创建了一个简单的PNG图像与白色物体和透明背景recommended by AppleiOS中的反锯齿自定义栏按钮图像

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

IOS不会为渲染图像添加消除锯齿 - 仅从代码绘制的项目。在保存到文件之前,您必须反映图像的别名。

从代码中取消映射图像的方法是绘制代码。

+0

感谢您的信息。我很惊讶那里不可能提供这个面具,并让iOS做反锯齿的肮脏工作并添加斜面。好吧。 – Pat

+0

是否可以从代码中绘制现有的.PNG?假设我有更大版本的图标,例如200x200。是否有可能通过编程将其缩小到40x40并应用插值使其看起来反​​锯齿? – Pat

+1

是的,这是可能的,iOS会自动执行。 – Jason