Objective c 绘制CGUIBezier曲线
大家好,我正在研究如何绘制上图中的形状。我一直在查看和阅读,但对如何使用UIBezierPath绘制曲线有点困惑。我真的找到了用CAShapeLayer和动画来画线的方法 到目前为止,我掌握的代码是:Objective c 绘制CGUIBezier曲线,objective-c,uibezierpath,cgpath,Objective C,Uibezierpath,Cgpath,大家好,我正在研究如何绘制上图中的形状。我一直在查看和阅读,但对如何使用UIBezierPath绘制曲线有点困惑。我真的找到了用CAShapeLayer和动画来画线的方法 到目前为止,我掌握的代码是: @synthesize animationLayer = _animationLayer; @synthesize pathLayer = _pathLayer; @synthesize penLayer = _penLayer; - (void) setupDrawingLayer {
@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];
}
解决这类问题的方法是在Illustrator等绘图程序中绘制形状。这清楚地显示了bezier曲线点需要到达的位置,以便获得我要跟踪的曲线。UIBezier路径通常以moveToPoint开始,以设置曲线的起点。然后,使用以下方法,它后面是任意数量的曲线段: –addLineToPoint: –addArcWithCenter:半径:起始角:终止角:顺时针: –addCurveToPoint:controlPoint1:controlPoint2: –添加四曲线点:控制点: 你没有明确说明你遇到了什么问题,所以我要跳过一步,假设你正在努力解决的是addCurveToPoint:controlPoint1:controlPoint2 此调用添加的线段从最近添加或移动到曲线中第一个参数的点开始绘制线段。其波动方式由控制点决定 理解其波动方式的最简单方法是,想象将第一个点(在前面的方法调用中建立)连接到第一个控制点(让我们将此控制点称为线段1)的直线,以及将第一个参数(正在添加的线段的终点)连接到第二个控制点的另一条直线(我们将此控制点称为线段2) 起点处的贝塞尔曲线与控制点线段1相切。它与曲线末端的控制点线段2相切 因此,如果要绘制具有多个Bezier的曲线,以便它们形成平滑线,则需要确保一条曲线的控制点线段2的坡度与连接到该曲线的下一条曲线的控制点线段1的坡度相同 从起点到第一个控制点以及终点到第二个控制点的距离决定了曲线的曲率 我的一个朋友这样想象。想象一艘宇宙飞船从A点行驶到B点。宇宙飞船开始时的航向由控制点线段1的坡度决定,速度由其长度决定。航向逐渐变为控制点线段2的坡度。同时,速度逐渐变慢G等于控制点线段2的长度。当太空船到达B点时,它与该线段相切