2

我正在应用渐变UIImage,我希望它在底部变暗,然后在中间慢慢变成透明或浅灰色。大部分都可以,但我有一个问题,就是我的图像颜色在这个渐变下的某些地方会反转。这看起来很烦人。我该如何解决?

为了您的方便,这是我的方法。

我尝试过选择不同的混合模式,但没有帮助。另一个问题是,如何让底部的黑色更加密集?

此方法无需任何额外代码即可工作。开始颜色是[UIColor blackColor],结束颜色是[UIColor clearColor]

- (UIImage *)imageWithGradient:(UIImage *)img startColor:(UIColor *)color1 endColor:(UIColor *)color2 {
    UIGraphicsBeginImageContextWithOptions(img.size, NO, img.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, img.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetBlendMode(context, kCGBlendModeDarken); // tried normal here, same results


    CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
    CGContextDrawImage(context, rect, img.CGImage);

    // Create gradient
    NSArray *colors = [NSArray arrayWithObjects:(id)color1.CGColor, (id)color2.CGColor, nil];
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColors(space, (__bridge CFArrayRef)colors, NULL);

    // Apply gradient
    CGContextClipToMask(context, rect, img.CGImage);
    CGContextDrawLinearGradient(context, gradient, CGPointMake(0,0), CGPointMake(0, img.size.height / 2.0), 0);
    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGGradientRelease(gradient);
    CGColorSpaceRelease(space);

    return gradientImage;
}
4

4 回答 4

13

试试这个

// Set image over layer
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = imageView.frame;

// Add colors to layer
UIColor *centerColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.25];
UIColor *endColor = [UIColor grayColor];
gradient.colors = [NSArray arrayWithObjects:
                               (id)[endColor CGColor],
                               (id)[centerColor CGColor],
                               (id)[endColor CGColor],
                               nil];

[imageView.layer insertSublayer:gradient atIndex:0];

只需根据您的要求更改 gradient.colors 数组。

于 2013-04-23T13:11:28.333 回答
5

Navnath 用 Swift 回答

var gradient = CAGradientLayer()
gradient.frame = imageView.frame
gradient.colors = [
    UIColor(white: 0, alpha: 0.25).CGColor,
    UIColor.grayColor().CGColor, 
    UIColor(white: 0, alpha: 0.25).CGColor
]
imageView.layer.insertSublayer(gradient, atIndex: 0)

Hope you find it useful

于 2015-08-31T14:24:30.663 回答
1

Slight correction to Navnath's and Francis's answers... gradient.frame needs to be set to imageView.bounds:

gradient.frame = imageView.bounds
于 2016-03-03T03:09:57.383 回答
0

尝试仅更改 alpha 以获得所需的结果。将图层放在现有图像的顶部。

于 2013-04-23T12:40:11.453 回答