美文网首页
iOS:给View添加渐变色

iOS:给View添加渐变色

作者: zxb有缘 | 来源:发表于2021-04-12 18:47 被阅读0次

    给View添加渐变色的方法有多种,这里采用CAGradientLayer来实现渐变效果。CAGradientLayer的好处在于绘制使用了硬件加速。

    CAGradientLayer在背景色上绘制颜色渐变,填充图层的形状(包括圆角)。
    

    一个简单的例子:

    UIView *colorView = [[UIView alloc] init];
    [colorView setFrame:CGRectMake(20, 160,
    self.view.frame.size.width - 40, self.view.frame.size.height - 320)];
    [self.view addSubview:colorView];

    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = colorView.bounds;
    gradient.colors = [NSArray arrayWithObjects:
    (id)[UIColor colorWithRed:0 green:143/255.0 blue:234/255.0 alpha:1.0].CGColor,
    (id)[UIColor colorWithRed:0 green:173/255.0 blue:234/255.0 alpha:1.0].CGColor,
    (id)[UIColor whiteColor].CGColor, nil];
    [colorView.layer addSublayer:gradient];

    效果如下:

    image

    CAGradientLayer属于QuartzCore,QuartzCore提供动画和动画显示层次功能的应用程序。
    CAGradientLayer有5个属性:

    colors: An array of CGColorRef
    objects defining the color of each gradient stop. Animatable.
    locations: An optional array of NSNumber objects defining the location of each gradient stop. Animatable.
    endPoint: The end point of the gradient when drawn in the layer’s coordinate space. Animatable.
    startPoint: The start point of the gradient when drawn in the layer’s coordinate space. Animatable.
    type: Style of gradient drawn by the layer.
    

    colors中设置渐变的颜色;locations中设置颜色的范围,大小在[0, 1]内,默认为平均;startPoint和endPoint设置渐变的起始位置,范围在[0, 1]内;type设置渐变样式,目前仅支持线性渐变(kCAGradientLayerAxial)。

    对角线渐变,渐变范围0.0,0.2,0.5,一定要确保locations
    数组和colors数组大小相同,否则会得到一个空白的渐变。

    AGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = colorView.bounds;
    gradient.colors = [NSArray arrayWithObjects:
    (id)[UIColor magentaColor].CGColor,
    (id)[UIColor cyanColor].CGColor,
    (id)[UIColor greenColor].CGColor, nil];
    gradient.startPoint = CGPointMake(0, 0);
    gradient.endPoint = CGPointMake(1, 1);
    gradient.locations = @[@0.0, @0.2, @0.5];
    [colorView.layer addSublayer:gradient];

    效果如下:

    image

    相关文章

      网友评论

          本文标题:iOS:给View添加渐变色

          本文链接:https://www.haomeiwen.com/subject/ivoxlltx.html