大家好,我正在研究如何绘制上图中的形状。我一直在寻找和阅读,但对如何使用 UIBezierPath 绘制曲线感到有些困惑。我发现了非常好的代码,它使用带有动画的 CAShapeLayer 来绘制线条。
到目前为止我的代码是:
@synthesize animationLayer = _animationLayer;
@synthesize pathLayer = _pathLayer;
@synthesize penLayer = _penLayer;
- (void) setupDrawingLayer
{
if (self.pathLayer != nil) {
[self.penLayer removeFromSuperlayer];
[self.pathLayer removeFromSuperlayer];
self.pathLayer = nil;
self.penLayer = nil;
}
CGPoint upperCurve = CGPointMake(101, 100);
CGPoint lowerCurve = CGPointMake(224,200);
UIBezierPath *path = [UIBezierPath bezierPath];
path.lineCapStyle = kCGLineCapRound;
path.miterLimit = -10.0f;
path.lineWidth = 10.0f;
[path moveToPoint:lowerCurve];
[path addQuadCurveToPoint:upperCurve controlPoint:lowerCurve];
CAShapeLayer *pathLayer = [CAShapeLayer layer];
pathLayer.frame = self.animationLayer.bounds;
pathLayer.path = path.CGPath;
pathLayer.strokeColor = [[UIColor blackColor] CGColor];
pathLayer.fillColor = nil;
pathLayer.lineWidth = 10.0f;
pathLayer.lineJoin = kCALineJoinBevel;
[self.animationLayer addSublayer:pathLayer];
self.pathLayer = pathLayer;
}
-(void) startAnimation
{
[self.pathLayer removeAllAnimations];
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 10.0;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[self.pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.animationLayer = [CALayer layer];
self.animationLayer.frame = CGRectMake(20.0f, 64.0f,
CGRectGetWidth(self.view.layer.bounds) - 40.0f,
CGRectGetHeight(self.view.layer.bounds) - 84.0f);
[self.view.layer addSublayer:self.animationLayer];
[self setupDrawingLayer];
[self startAnimation];
}