【问题标题】:CGMutablePath always starts at 0,0CGMutablePath 总是从 0,0 开始
【发布时间】:2015-09-15 13:40:05
【问题描述】:

学习使用 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];

它做了我想要的,就是绘制一个图形轴。

【问题讨论】:

  • 您在这里使用CGPath 有什么特别的原因吗? UIBezierPath 有方法可以做同样的事情,而不必创建一个单独的对象。 (或者,您可以使用 CGPath 完成所有工作,因为您以后需要它;不过,您绝对不需要两者。只需在 CAShapeLayer 上设置填充规则;如果您需要它,那就是它所属的地方,但它没有没有任何意义,因为无论如何你都没有填满。)
  • 我已经更新了代码,它可以工作,但我还在混合 CGPath 和 UIBezierPath 吗?
  • 您更新的代码看起来不错。您以正确的方式使用UIBezierPath 和CGPath。我看到你删除了bounds。你还在烦恼吗?
  • 嗨。现在没有一切正常。感谢您的帮助和建议...

标签: ios uiview quartz-graphics uibezierpath


【解决方案1】:

你的问题在这里:

lines.bounds = CGPathGetBoundingBox(lines.path);

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

【讨论】:

    猜你喜欢
    • 2013-12-25
    • 2012-12-21
    • 2020-06-07
    • 1970-01-01
    • 2022-01-09
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多