我需要制作 2D 渐变。我有它的第一部分从颜色到清晰颜色的渐变垂直方向:
+ (void)addFadeout:(UIView *) view withColor:(UIColor *)color {
UIColor * halfClearColor = [color colorWithAlphaComponent:0];
CALayer *layer = view.layer;
layer.masksToBounds = YES;
CAGradientLayer *shineLayer = [CAGradientLayer layer];
shineLayer.frame = layer.bounds;
shineLayer.colors = @[
(id)color.CGColor,
(id)halfClearColor.CGColor];
shineLayer.locations = @[
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:1.0f]];
[view.layer insertSublayer:shineLayer atIndex:0];
}
但我还需要能够在水平方向添加多种颜色,它们要么一起淡化,要么分别显示(仍然具有垂直渐变)。我知道我可以把它们加在一起,但这不是我想要的。你会怎么做?
它可能是这样的,但我似乎无法连接这些部分: http ://cupsofcocoa.com/tag/gradient/ https://developer.apple.com/library/mac/#documentation/graphicsimaging/conceptual/用quartz2d/dq_shadings/dq_shadings.html绘图
编辑1:
这就是我现在得到的:
可能不清楚我想要什么。我还想要多个颜色之间沿 x 轴的渐变。所以我得到了这样的东西:(替换红色)
解决方案:
+ (void)addFadeout:(UIView *) view withColors:(NSArray *)colors { //CGColors
UIColor * someColor = [UIColor colorWithCGColor:((__bridge CGColorRef)[colors lastObject])];//only alpha channel used with more than one color
UIColor * halfClearColor = [someColor colorWithAlphaComponent:0];
CALayer *layer = view.layer;
layer.masksToBounds = YES;
CAGradientLayer *transparencyLayer = [CAGradientLayer layer];
transparencyLayer.frame = layer.bounds;
transparencyLayer.colors = @[
(id)someColor.CGColor,
(id)halfClearColor.CGColor];
transparencyLayer.locations = @[
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:1.0f]];
if(colors.count > 1){
CAGradientLayer * multiColoredLayer = [self getMultiColoredLayerWithColors:colors inLayer:layer];
multiColoredLayer.mask = transparencyLayer;
[view.layer insertSublayer:multiColoredLayer atIndex:0];
}
else{
[view.layer insertSublayer:transparencyLayer atIndex:0];
}
}
+ (CAGradientLayer *)getMultiColoredLayerWithColors:(NSArray *)colors inLayer:(CALayer *)layer{ //CGColors
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = layer.bounds;
gradientLayer.colors = colors;
gradientLayer.startPoint = CGPointMake(0, 0.5);
gradientLayer.endPoint = CGPointMake(1.0, 0.5);
return gradientLayer;
}