我正在对 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;
}
最佳答案
试试这个
// 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];
只需更改渐变数组。颜色取决于您的要求。
关于ios - 将渐变应用于 UIImage - 如何去除颜色反转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16169499/