How can I get a image with gradient without blended layer?

Viewed 274

In my UITableViewCell there is a background UIImageView. If I use the raw image download from server there is no blended layer showed on that ImageView. But if I add gradient to the image downloaded (some images contain lots of white space which make it hard to see the front label, so I have to make the image darker), blended layer showed. How can I add gradient to the image while avoiding blended layer?

enter image description here enter image description here

The code used to generate image with gradient is showed below:

- (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;
}
1 Answers
Related