3
在我的UITableViewCell中有一个背景UIImageView。如果我使用从服务器下载的原始图像,则该ImageView上不会显示混合图层。但是,如果我为下载的图像添加渐变(某些图像包含很多空白区域,这使得很难看到前面的标签,所以我必须使图像变暗),混合图层显示。如何在避免混合图层的同时向图像添加渐变?如何获得没有混合图层的渐变图像?
用于产生具有梯度图像的代码如下示:
- (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;
}
您可以在图像上方添加UIView,并将其设置为黑色或灰色,并将alpha设置为0.3,例如 –
@DianaProdan它会得到与我的解决方案相同的结果。 – highsun16
你如何添加渐变?您是使用'CAGradientLayer'还是使用Core Graphics在图像上绘制渐变图像来创建新图像? –