简体   繁体   中英

UIView with CAShapeLayer does not display CAGradientLayer

I try to apply a radiant to a custom shaped UIView

The gradiant category I used if well tested and used in other part of my code. However, I cannot get it to function properly in a custom shaped view created using a CAShapeLayer

In my UIView category:

@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

In my UIView subclass:

   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

The view appear with whatever backgroundColor was assigned to it. I tried setting the gradient after applying the mask, without much results.

In code

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

change

gradient.frame = self.frame;

to

gradient.frame = self.bounds;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM