ios – 使用CAShapeLayer的UIView不显示CAGradientLayer

我尝试将辐射应用于自定义形状的UIView

我使用的渐变类别如果经过充分测试并在我的代码的其他部分中使用.
但是,我不能让它在使用CAShapeLayer创建的自定义形状视图中正常运行

在我的UIView类别中:

@implementation UIView (Grandiant)

- (void)addGradientBackgroundFromTopColor:(UIColor *)topColor toBottomColor:(UIColor *)bottomColor {
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = self.frame;
    gradient.colors = [NSArray arrayWithObjects:(id)[topColor CGColor], (id)[bottomColor CGColor], nil];
    [self.layer insertSublayer:gradient atIndex:0];
}

@end

在我的UIView子类中:

   override func awakeFromNib() {
        super.awakeFromNib()
          self.addGradientBackgroundFromTopColor(UIColor(red: 221.0/256.0, green: 0.5, blue: 32.0/256.0, alpha: 1), toBottomColor: UIColor(red: 220.0/256.0, green: 94.0/256.0, blue: 17.0/256.0, alpha: 1))
    }

    override var frame: CGRect {
    didSet {
        let bezierpath = UIBezierPath()
        bezierpath.moveToPoint(CGPoint(x: 0, y: 0)) // 1
        bezierpath.addLineToPoint(CGPoint(x: 0, y:  frame.height - triangleHeight)) // 2
        bezierpath.addLineToPoint(CGPoint(x: frame.width / 2, y: frame.height))// 3
        bezierpath.addLineToPoint(CGPoint(x: frame.width, y: frame.height - triangleHeight))// 4
        bezierpath.addLineToPoint(CGPoint(x: frame.width, y: 0))// 5
        let mask = CAShapeLayer()
        mask.frame = bounds
        mask.path = bezierpath.CGPath
        layer.mask = mask

该视图随着backgroundColor分配给它而出现.
我尝试在应用蒙版后设置渐变,但没有太多结果.

最佳答案 在代码中

- (void)addGradientBackgroundFromTopColor:(UIColor *)topColor toBottomColor:(UIColor *)bottomColor {
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = self.frame;
    gradient.colors = [NSArray arrayWithObjects:(id)[topColor CGColor], (id)[bottomColor CGColor], nil];
    [self.layer insertSublayer:gradient atIndex:0];
}

更改

gradient.frame = self.frame;

gradient.frame = self.bounds;
点赞