Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between closing the bezier path using closePath function and closing it manually?

I am trying to make a rectangle using UIBezierPath. I adopted two different ways to draw it. Also, I increased the stroke width to 25 px.

First method : Using closePath

UIBezierPath *bpath = [UIBezierPath bezierPath];
    
[bpath moveToPoint:CGPointMake(x, y)];
[bpath addLineToPoint:CGPointMake(x + w, y)];
[bpath addLineToPoint:CGPointMake(x + w, y + h)];
[bpath addLineToPoint:CGPointMake(x, y + h)];
[bpath closePath];

Output:

Using closePath

Second method : Closing the path manually

UIBezierPath *bpath = [UIBezierPath bezierPath];
    
[bpath moveToPoint:CGPointMake(x, y)];
[bpath addLineToPoint:CGPointMake(x + w, y)];
[bpath addLineToPoint:CGPointMake(x + w, y + h)];
[bpath addLineToPoint:CGPointMake(x, y + h)];
[bpath addLineToPoint:CGPointMake(x, y)];

Output:

Closing path manually

In the documentation for closePath it says This method closes the current subpath by creating a line segment between the first and last points in the subpath. This method subsequently updates the current point to the end of the newly created line segment, which is also the first point in the now closed subpath.

And in second method I am creating the line segment between first and last points. So, why in the second method rectangle is not completely stroked?

Note: Difference between these methods is only visible when stroke width is increased significantly.

like image 804
blancos Avatar asked Sep 12 '14 11:09

blancos


1 Answers

The difference is that the [closePath] method actually adds an additional path element to the underlying CGPath that backs the UIBezierPath.

If you use [closePath], then an additional CGPathElement with a type of kCGPathElementCloseSubpath will be appended to the end of the path immediately after that last line segment.

This is particularly important when using the [containsPoint:] method of a UIBezierPath from the docs:

A point is not considered to be enclosed by the path if it is inside an open subpath, regardless of whether that area would be painted during a fill operation. Therefore, to determine mouse hits on open paths, you must create a copy of the path object and explicitly close any subpaths (using the closePath method) before calling this method.

like image 136
adam.wulf Avatar answered Nov 05 '22 14:11

adam.wulf