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