使用CAShapeLayer的UIView不显示CAGradientLayer

时间:2015-01-16 09:40:10

标签: ios uiview cashapelayer cagradientlayer

我尝试将自然光线应用于自定义UIView

我使用的gradiant类别经过充分测试并在我的代码的其他部分使用。 但是,我无法在使用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分配给它而出现。 我尝试在应用蒙版后设置渐变,但没有太多结果。

1 个答案:

答案 0 :(得分:2)

代码

- (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;