将渐变应用于虚线UIBezierPath

时间:2018-07-20 20:03:08

标签: ios gradient uibezierpath

这个渐变是我想在虚线UIBezierPath上实现的。
enter image description here

尝试此代码失败。

let gradient = CAGradientLayer()
gradient.frame = outerPath.bounds
gradient.colors = [UIColor.red.cgColor, UIColor.yellow.cgColor]

// mask
let shapeMask = CAShapeLayer()
shapeMask.path = outerPath.cgPath
self.insertSublayer(gradient, at: 0)

2 个答案:

答案 0 :(得分:2)

让CAShapeLayer制作一个虚线蒙版。

class
TheView: UIView {

    required init?( coder aDecoder: NSCoder ) {
        super.init( coder: aDecoder )

        let outerPath = UIBezierPath( ovalIn: bounds.insetBy( dx: 20, dy: 20 ) )

        let gradient = CAGradientLayer()
        gradient.frame = bounds
        gradient.colors = [ UIColor.red.cgColor, UIColor.yellow.cgColor ]

        let shapeMask = CAShapeLayer()
        shapeMask.path = outerPath.cgPath
        shapeMask.lineWidth = 8
        shapeMask.lineDashPhase = 0
        shapeMask.lineDashPattern = [ 6, 2 ]
        shapeMask.lineCap = .butt
        shapeMask.lineJoin = .bevel
        shapeMask.strokeColor = UIColor.black.cgColor   //  Any color
        shapeMask.fillColor = nil
        gradient.mask = shapeMask
        layer.addSublayer( gradient )
    }
}

enter image description here

答案 1 :(得分:0)

我认为最好的方法是自己填充每个正方形的颜色。在这种情况下,开始颜色为绿色,结束颜色为红色,那么如何计算内部颜色?

您可以看到此演示:

typedef struct{
   float red;
   float green;
   float blue;
} TFColor;

- (void)viewDidLoad {
    [super viewDidLoad];

    TFColor start = {0,1,0}; //green
    TFColor end = {1,0,0}; //red

    for (int i = 0; i<20; i++) {
        UIView *square = [[UIView alloc] initWithFrame:CGRectMake(150, 20*i, 75, 20)];

        //the lerp rate changes from 1 to 0.
        TFColor lerpColor = [self lerp:(19-i)/19.0f first:start second:end];
        square.backgroundColor = [UIColor colorWithRed:lerpColor.red green:lerpColor.green blue:lerpColor.blue alpha:1];
        [self.view addSubview:square];
    }
}

#define lerpNum(a,b,r) (a*r+(1.0f-r)*b)

-(TFColor)lerp:(CGFloat)rate first:(TFColor)firstColor second:(TFColor)secondColor{
    TFColor result;
    result.red = lerpNum(firstColor.red, secondColor.red, rate);
    result.green = lerpNum(firstColor.green, secondColor.green, rate);
    result.blue = lerpNum(firstColor.blue, secondColor.blue, rate);

    return result;
}

您可以使用每个正方形的角度来获得平滑的lerp率。