Jonathan Dixon Jonathan Dixon - 1 year ago 110
Objective-C Question

Drawing a Hexagon with UIBezierPath (point first)

I am trying to draw a Hexagon using UIBezierPath and ZEPolygon, it works great but my hexagon is flat on top. I have tried everything to get it to draw form a point in the middle including a 180 degree transform on the path which work but everything else break.

This is how it looks now

This is how i would like it to look

My code is below

UIImageView *maskedImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]];

UIBezierPath *nonagon = [UIBezierPath bezierPathWithPolygonInRect:maskedImageView.frame numberOfSides:6];

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = nonagon.CGPath;

maskedImageView.layer.mask = shapeLayer;

[self.view addSubview:maskedImageView];

This is the library i used for the drawing the bezier path

Thanks for any help

Answer Source

When you rotate a UIBezierPath with a CGTransform, it will be rotated around the point (0,0), and for your path the point (0,0) is the top left corner of your shape. This is why the offset is incorrect when you just rotate by 90 degrees w/o doing anything else - its rotating around the wrong point.

So before you rotate, you need to center the path to the point (0,0), then rotate it, then move it back so that (0,0) is at its top left.

the following code will rotate the polygon 90 degrees:

// get the size of the image, we'll need this for our path and for later too
CGRect boundsForPoly = maskedImageView.frame;
// create our path inside the rect
UIBezierPath *nonagon = [UIBezierPath bezierPathWithPolygonInRect:boundsForPoly numberOfSides:6];
// center the polygon on (0,0)
[nonagon applyTransform:CGAffineTransformMakeTranslation(-boundsForPoly.size.width/2, -boundsForPoly.size.height/2)];
// rotate it 90 degrees
[nonagon applyTransform:CGAffineTransformMakeRotation(M_PI/2)];
// now move it back so that the top left of its bounding box is (0,0)
[nonagon applyTransform:CGAffineTransformMakeTranslation(nonagon.bounds.size.width/2, nonagon.bounds.size.height/2)];

this will rotate the polygon 90 degrees, and keep it's top left corner at (0,0)

The blue outline is your path before, and the green outline is after the rotation:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download