iOS渐变与圆角共存

  • 内容
  • 评论
  • 相关

圆角弧度同样情况下

// 创建CAGradientLayer
CAGradientLayer *gradientLayer = [CAGradientLayer layer];

// 设置渐变色
gradientLayer.colors = @[(__bridge id)[UIColor colorWithRed:77.0/255.0 green:144.0/255.0 blue:255.0/255.0 alpha:1.0].CGColor,
                            (__bridge id)[UIColor colorWithRed:206.0/255.0 green:100.0/255.0 blue:255.0/255.0 alpha:1.0].CGColor];

// 设置渐变方向
gradientLayer.startPoint = CGPointMake(0.0, 0.5);
gradientLayer.endPoint = CGPointMake(1.0, 0.5);

// 设置frame
gradientLayer.frame = self.orderBg.bounds;

// 创建绘制圆角的Bezier路径
UIBezierPath *roundedRectPath = [UIBezierPath bezierPathWithRoundedRect:gradientLayer.bounds 
                          byRoundingCorners:UIRectCornerAllCorners
                                cornerRadii:CGSizeMake(30.0, 10.0)];

// 创建一个shape层作为gradientLayer的mask
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = roundedRectPath.CGPath;

// 将maskLayer赋值给gradientLayer的mask
gradientLayer.mask = maskLayer;

// 加入渐变层到我们的视图
[self.orderBg.layer insertSublayer:gradientLayer atIndex:0];

圆角弧度不同时

// 创建CAGradientLayer
CAGradientLayer *gradientLayer = [CAGradientLayer layer];

// 设置渐变色
gradientLayer.colors = @[(__bridge id)[UIColor colorWithRed:77.0/255.0 green:144.0/255.0 blue:255.0/255.0 alpha:1.0].CGColor,
                            (__bridge id)[UIColor colorWithRed:206.0/255.0 green:100.0/255.0 blue:255.0/255.0 alpha:1.0].CGColor];

// 设置渐变方向
gradientLayer.startPoint = CGPointMake(0.0, 0.5);
gradientLayer.endPoint = CGPointMake(1.0, 0.5);

// 设置frame
gradientLayer.frame = self.orderBg.bounds;

// 创建绘制圆角的Bezier路径
UIBezierPath *roundedRectPath = [UIBezierPath bezierPathWithRoundedRect:gradientLayer.bounds 
                          byRoundingCorners:UIRectCornerAllCorners
                                cornerRadii:CGSizeMake(30.0, 10.0)];

// 创建一个shape层作为gradientLayer的mask
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = roundedRectPath.CGPath;

// 将maskLayer赋值给gradientLayer的mask
gradientLayer.mask = maskLayer;

// 加入渐变层到我们的视图
[self.orderBg.layer insertSublayer:gradientLayer atIndex:0];

评论

0条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注