CGMutablePath 总是从 0,0 开始

CGMutablePath always starts at 0,0

学习使用 UIBezierPath 路径。我可以在我的 UIView 中绘制一条简单的线,但原点始终为 0,0。我错过了什么?

简单代码:

CGMutablePathRef cgPath = CGPathCreateMutable();

UIBezierPath *aPath = [UIBezierPath bezierPath];

CGPathMoveToPoint(cgPath, NULL, 100, 100);
CGPathAddLineToPoint(cgPath, NULL, 200,200);

aPath.CGPath = cgPath;
aPath.usesEvenOddFillRule = YES;

CAShapeLayer *lines = [CAShapeLayer layer];
lines.path = aPath.CGPath;
lines.bounds = CGPathGetBoundingBox(lines.path);
lines.strokeColor = [UIColor whiteColor].CGColor;
lines.fillColor = [UIColor clearColor].CGColor; /*if you just want lines*/
lines.lineWidth = 3;

[self.UIView.layer addSublayer:lines];

CGPathRelease(cgPath);

我的起点也设置为 100,100,画一条线到 200,200。但它总是从 0,0 左右开始。

更新的代码 - 但我是否仍在混合使用 UIBezierPath 和 CGPath?

static CGFloat thickness = 0.5;
static CGFloat shapeSizex = 300;
static CGFloat shapeSizey = 150;
static CGFloat xanchor = 20; // bottom-left corner x
static CGFloat yanchor = 180; // bottom-left corner y

UIBezierPath *axisPath = [UIBezierPath bezierPath];
[axisPath moveToPoint:CGPointMake(xanchor, yanchor-shapeSizey)];
[axisPath addLineToPoint:CGPointMake(xanchor, yanchor)];
[axisPath addLineToPoint:CGPointMake(xanchor+shapeSizex, yanchor)];

CAShapeLayer *lines = [CAShapeLayer layer];
lines.path = axisPath.CGPath;
lines.strokeColor = [UIColor whiteColor].CGColor;
lines.lineWidth = thickness;

[self.ChartViewOutlet.layer addSublayer:lines];

它完成了我想要的,即绘制图形轴。

您的问题在这里:

lines.bounds = CGPathGetBoundingBox(lines.path);

您已重新定义图层以环绕路径。所以当你绘制它的时候,它会变形以将绘制路径的中心放在图层的中心。