2014-02-21 101 views
0

我有問題了解以下方法的原因,以返回明顯像素化的圖像。我已經仔細檢查了圖像的大小,並且沒有問題。更重要的是,如果不着色,圖像邊緣平滑,並且缺乏像素化。顏色有色UIImages獲得像素化

基於IOS7 ImageView的tintColor屬性設置圖像的方法工作正常,但是我想知道下面的代碼有什麼問題,因爲它似乎適用於除我之外的其他人。謝謝!

- (UIImage *)imageTintedWithColor:(UIColor *)color 
{ 
if (color) { 
    UIImage *img = self; // The method is a part of UIImage category, hence the "self" 
    UIGraphicsBeginImageContext(img.size); 

    // get a reference to that context we created 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    // set the fill color 
    [color setFill]; 

    // translate/flip the graphics context (for transforming from CG* coords to UI* coords 
    CGContextTranslateCTM(context, 0, img.size.height); 
    CGContextScaleCTM(context, 1.0, -1.0); 

    // set the blend mode to color burn, and the original image 
    CGContextSetBlendMode(context, kCGBlendModeColorBurn); 
    CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height); 
    CGContextDrawImage(context, rect, img.CGImage); 

    // set a mask that matches the shape of the image, then draw (color burn) a colored rectangle 
    CGContextSetBlendMode(context, kCGBlendModeSourceIn); 
    CGContextAddRect(context, rect); 
    CGContextDrawPath(context,kCGPathFill); 

    // generate a new UIImage from the graphics context we drew onto 
    UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    //return the color-burned image 
    return coloredImg; 
} 

return self; 

} 

回答

1

改變這一行:

UIGraphicsBeginImageContext(img.size); 

到:

UIGraphicsBeginImageContextWithOptions(img.size, NO, 0); 

如果您的圖片將永遠不會有一個透明度,改變NOYES

+0

你是完全正確的!從文檔:UIGraphicsBeginImageContext() - 此函數等效於調用UIGraphicsBeginImageContextWithOptions函數,其opaque參數設置爲NO並且縮放因子爲1.0'。所以差異是「比例因子」。 @rmaddy,你能解釋比例因子0和1之間有什麼區別嗎? – Michael

+1

'0'的值表示根據設備確定是否應使用'1'或'2'的值。視網膜設備將導致使用「2」,而非視網膜設備導致使用「1」。 – rmaddy

+0

非常棒的答案,非常感謝 – Michael