0
votes

Learning to use a UIBezierPath path. I can draw a simple line within my UIView but the origin is always 0,0. What am I missing?

Simple Code:

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);

I set my start point too 100,100 and draw a line to 200,200. But it always start somewhere around 0,0.

UPDATED CODE - But am I still mixing between UIBezierPath and 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];

It does what I wanted which is to draw a graph axis.

1
Any particular reason you're using CGPath here? UIBezierPath has methods on it to do exactly the same thing without having to create a separate object. (Alternately you could do all of the work with CGPath, since you need it later; you definitely don't need both, though. Just set the fill rule on the CAShapeLayer; that's where it belongs if you need it, but it doesn't make any sense since you're not filling anyway.)Rob Napier
I've update the code, it works but am I still mixing bewteen CGPath and UIBezierPath?user5308141
Your updated code looks fine. You're using UIBezierPath and CGPath in the correct ways. I see you removed the bounds. Are you still having trouble?Rob Napier
Hi. No all working fine now. Thanks for the help and advice...user5308141

1 Answers

0
votes

Your problem is here:

lines.bounds = CGPathGetBoundingBox(lines.path);

You're redefined the layer to wrap around the path. So when you draw it, it's transformed to put the center of the drawn path in the center of the layer.