2016-03-15 47 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通道。