画贝塞尔曲线,通过四个点算出两个控制点,画出连接中间两个点的曲线
- (void)addCurveWithPoint0:(CGPoint)point0
point1:(CGPoint)point1
point2:(CGPoint)point2
point3:(CGPoint)point3
path:(UIBezierPath*)path {
CGFloat x0 = point0.x, y0 = point0.y;
CGFloat x1 = point1.x, y1 = point1.y;
CGFloat x2 = point2.x, y2 = point2.y;
CGFloat x3 = point3.x, y3 = point3.y;
CGFloat smooth_value =0.6;
CGFloat ctrl1_x;
CGFloat ctrl1_y;
CGFloat ctrl2_x;
CGFloat ctrl2_y;
CGFloat xc1 = (x0 + x1) /2.0;
CGFloat yc1 = (y0 + y1) /2.0;
CGFloat xc2 = (x1 + x2) /2.0;
CGFloat yc2 = (y1 + y2) /2.0;
CGFloat xc3 = (x2 + x3) /2.0;
CGFloat yc3 = (y2 + y3) /2.0;
CGFloat len1 = sqrt((x1-x0) * (x1-x0) + (y1-y0) * (y1-y0));
CGFloat len2 = sqrt((x2-x1) * (x2-x1) + (y2-y1) * (y2-y1));
CGFloat len3 = sqrt((x3-x2) * (x3-x2) + (y3-y2) * (y3-y2));
CGFloat k1 = len1 / (len1 + len2);
CGFloat k2 = len2 / (len2 + len3);
CGFloat xm1 = xc1 + (xc2 - xc1) * k1;
CGFloat ym1 = yc1 + (yc2 - yc1) * k1;
CGFloat xm2 = xc2 + (xc3 - xc2) * k2;
CGFloat ym2 = yc2 + (yc3 - yc2) * k2;
ctrl1_x = xm1 + (xc2 - xm1) * smooth_value + x1 - xm1;
ctrl1_y = ym1 + (yc2 - ym1) * smooth_value + y1 - ym1;
ctrl2_x = xm2 + (xc2 - xm2) * smooth_value + x2 - xm2;
ctrl2_y = ym2 + (yc2 - ym2) * smooth_value + y2 - ym2;
[path addCurveToPoint:CGPointMake(x2, y2) controlPoint1:CGPointMake(ctrl1_x, ctrl1_y) controlPoint2:CGPointMake(ctrl2_x, ctrl2_y)];
}
实现渐变的方法:
CAShapeLayer *curevePathLayer = [CAShapeLayer layer];
curevePathLayer.fillColor = [[UIColor clearColor] CGColor];
curevePathLayer.strokeColor = [self.mainColor CGColor];
curevePathLayer.path = path.CGPath;
curevePathLayer.lineWidth = 5.0;
curevePathLayer.lineCap = kCALineCapRound;
curevePathLayer.lineJoin = kCALineCapRound;
[self.layer addSublayer:curevePathLayer];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = CGRectMake(0, 0, self.width, self.height);
NSMutableArray *gradientColors = [[NSMutableArray alloc] init];
[gradientColors en_addObject:(id)[[UIColor darkGrayColor] CGColor]];
[gradientColors en_addObject:(id)[[UIColor lightGrayColor] CGColor]];
[gradientLayer setColors:gradientColors];
[gradientLayer setStartPoint:CGPointMake(0, 0.5)];
[gradientLayer setEndPoint:CGPointMake(1, 0.5)];
[gradientLayer setMask:curevePathLayer];
[self.layer addSublayer:gradientLayer];