我尝试将辐射线应用于自定义形状的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;