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在圖像上繪製漸變圖像來創建新圖像? –