如何在iOS中使用渐变位置?

Mat*_*ier 5 hex gradient colors ios

我正在研究一个在Xcode中使用颜色的小项目.想知道渐变位置的作用.

我注意到gradientLayer.locations = [0.0,1.0]会使它垂直,所以我认为gradientLayer.locations = [0.5,0.5]会使它成为水平?

[0.5,0.5] - 导致2块颜色堆叠在彼此之上,没有渐变[0.0,1.0] - 导致我正在寻找的渐变,2种垂直颜色,带有渐变

我知道它有点模糊,但在这里寻找解释.这对我来说没什么意义.

谢谢,

马特

sch*_*dt9 16

文件说:

渐变停止指定为0到1之间的值.值必须单调递增.

所以locations实际上与渐变方向无关.关于后者,请参考这个问题.位置意味着梯度停止的位置,例如.在第一个视图中,红色从0(顶部)开始,到0.5(中间)结束,因此再到底部只能是纯蓝色.如果给出[0.5,0.5],则意味着两个渐变都应该从中间开始结束,因此颜色根本不会混合.

生成以下渐变的代码:

@interface TestViewController ()

@property (strong, nonatomic) IBOutlet UIView *view1;
@property (strong, nonatomic) IBOutlet UIView *view2;
@property (strong, nonatomic) IBOutlet UIView *view3;
@property (strong, nonatomic) IBOutlet UIView *view4;

@end

@implementation TestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *views = @[_view1, _view2, _view3, _view4];

    for (UIView *view in views) {
        view.layer.borderWidth = 1;
    }

    // 1
    CAGradientLayer *gradient = [CAGradientLayer new];
    gradient.colors = @[(id)[UIColor redColor].CGColor, (id)[UIColor blueColor].CGColor];
    gradient.frame = _view1.bounds;
    gradient.locations = @[@0.0, @0.5];
    [_view1.layer insertSublayer:gradient atIndex:0];

    // 2
    gradient = [CAGradientLayer new];
    gradient.colors = @[(id)[UIColor redColor].CGColor, (id)[UIColor blueColor].CGColor];
    gradient.frame = _view2.bounds;
    gradient.locations = @[@0.5, @1.0];
    [_view2.layer insertSublayer:gradient atIndex:0];

    // 3
    gradient = [CAGradientLayer new];
    gradient.colors = @[(id)[UIColor redColor].CGColor, (id)[UIColor blueColor].CGColor, (id)[UIColor greenColor].CGColor];
    gradient.frame = _view2.bounds;
    gradient.locations = @[@0.0, @0.5, @1.0];
    [_view3.layer insertSublayer:gradient atIndex:0];

    // 4
    gradient = [CAGradientLayer new];
    gradient.colors = @[(id)[UIColor redColor].CGColor, (id)[UIColor blueColor].CGColor, (id)[UIColor greenColor].CGColor];
    gradient.frame = _view4.bounds;
    gradient.locations = @[@0.0, @0.8, @1.0];
    [_view4.layer insertSublayer:gradient atIndex:0];
}

@end
Run Code Online (Sandbox Code Playgroud)

梯度