Add arrow to UIBezierPath

I need your help:

I am trying to create a graph using UIBezierPaths with variable width and consisting of a bezier curve with two control points. Now I would like to add arrows to the end (right side) of these paths. Is there a way to do this by adding a subpath with a smaller line width that contains the triangle? here is a rough picture of some of the paths to which I would like to add arrows:

enter image description here

Thank you for your help!

+3


source to share


1 answer


Let's say you've drawn one of these arcs:

UIBezierPath *path = [UIBezierPath bezierPath];

[path moveToPoint:point1];
[path addQuadCurveToPoint:point3 controlPoint:point2];

CAShapeLayer *shape = [CAShapeLayer layer];
shape.path = path.CGPath;
shape.lineWidth = 10;
shape.strokeColor = [UIColor blueColor].CGColor;
shape.fillColor = [UIColor clearColor].CGColor;
shape.frame = self.view.bounds;
[self.view.layer addSublayer:shape];

      

You can use atan2

to calculate the angle from the control point to the end point:

CGFloat angle = atan2f(point3.y - point2.y, point3.x - point2.x);

      

Note: It doesn't really matter if you use a bezier square or a cube, the idea is the same. Calculate the angle from the last control point to the end point.

Then you can place the arrow by calculating the angles of the triangle like this:



CGFloat distance = 15.0;
path = [UIBezierPath bezierPath];
[path moveToPoint:point3];
[path addLineToPoint:[self calculatePointFromPoint:point3 angle:angle + M_PI_2 distance:distance]]; // to the right
[path addLineToPoint:[self calculatePointFromPoint:point3 angle:angle          distance:distance]]; // straight ahead
[path addLineToPoint:[self calculatePointFromPoint:point3 angle:angle - M_PI_2 distance:distance]]; // to the left
[path closePath];

shape = [CAShapeLayer layer];
shape.path = path.CGPath;
shape.lineWidth = 2;
shape.strokeColor = [UIColor blueColor].CGColor;
shape.fillColor = [UIColor blueColor].CGColor;
shape.frame = self.view.bounds;
[self.view.layer addSublayer:shape];

      

Where we use sinf

and cosf

to calculate angles as follows:

- (CGPoint)calculatePointFromPoint:(CGPoint)point angle:(CGFloat)angle distance:(CGFloat)distance {
    return CGPointMake(point.x + cosf(angle) * distance, point.y + sinf(angle) * distance);
}

      

This gives something similar:

enter image description here

Clearly, just adjust the parameters distance

to control the shape of the triangle.

+8


source







All Articles