2016-03-15 35 views
3

在我的UITableViewCell中有一個背景UIImageView。如果我使用從服務器下載的原始圖像,則該ImageView上不會顯示混合圖層。但是,如果我爲下載的圖像添加漸變(某些圖像包含很多空白區域,這使得很難看到前面的標籤,所以我必須使圖像變暗),混合圖層顯示。如何在避免混合圖層的同時向圖像添加漸變?如何獲得沒有混合圖層的漸變圖像?

enter image description here enter image description here

用於產生具有梯度圖像的代碼如下示:

- (UIImage *)gs_imageWithDownsideShadow { 
    return [self gs_imageWithShadow:@[[UIColor gs_colorWithSameRGB:0 alpha:0.3], [UIColor gs_colorWithSameRGB:0 alpha:0.5]]]; 
} 

- (UIImage *)gs_imageWithShadow:(NSArray *)colors 
{ 
    CGSize size = self.size; 
    CGRect rect = CGRectMake(0, 0, size.width, size.height); 

    UIGraphicsBeginImageContextWithOptions(size, NO, UIScreen.mainScreen.scale); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextTranslateCTM(context, 0, self.size.height); 
    CGContextScaleCTM(context, 1.0, -1.0); 
    CGContextDrawImage(context, rect, self.CGImage); 

    CGFloat locations[] = {0.0, 1.0}; 
    NSMutableArray *colorRefs = [[NSMutableArray alloc] init]; 
    for (UIColor *color in colors) { 
     [colorRefs addObject:(__bridge id)color.CGColor]; 
    } 

    CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB(); 
    CGGradientRef gradient = CGGradientCreateWithColors(baseSpace, (__bridge CFArrayRef)colorRefs, locations); 

    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect)); 
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect)); 

    CGContextSaveGState(context); 
    CGContextAddRect(context, rect); 
    CGContextClip(context); 
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0); 
    CGContextRestoreGState(context); 

    CGGradientRelease(gradient); 
    CGColorSpaceRelease(baseSpace); 

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return newImage; 
} 
+0

您可以在圖像上方添加UIView,並將其設置爲黑色或灰色,並將alpha設置爲0.3,例如 –

+0

@DianaProdan它會得到與我的解決方案相同的結果。 – highsun16

+0

你如何添加漸變?您是使用'CAGradientLayer'還是使用Core Graphics在圖像上繪製漸變圖像來創建新圖像? –

回答

2

阿層,其contents是具有alpha通道的圖像必須與它後面的層混合。 (iOS假定圖像具有透明度,如果它具有Alpha通道;它不檢查任何alpha是否小於1.0。)

您正在創建帶alpha通道的漸變圖像,因爲您將NO傳遞給UIGraphicsBeginImageContextWithOptionsopaque參數。

假設所有的源圖像的其實都是不透明的,你可以(也應該)通過傳遞YES創建不透明的梯度化的圖像:

UIGraphicsBeginImageContextWithOptions(size, YES, UIScreen.mainScreen.scale); 

傳遞YES告訴UIKit中創建一個圖形上下文,並最終一個圖像,沒有alpha通道。