Ios 使用UIBezierPath绘制六边形(点优先)

Ios 使用UIBezierPath绘制六边形(点优先),ios,objective-c,uibezierpath,Ios,Objective C,Uibezierpath,我正在尝试用UIBezierPath和ZEPolygon画一个六边形,效果很好,但我的六边形顶部是平的。我已经尝试了一切,让它在中间形成一个点,包括一个180度的变换,在路径上工作,但是其他的东西都破了。 我的代码在下面 UIImageView *maskedImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]]; UIBezierPath *nonagon = [UIBezierP

我正在尝试用UIBezierPath和ZEPolygon画一个六边形,效果很好,但我的六边形顶部是平的。我已经尝试了一切,让它在中间形成一个点,包括一个180度的变换,在路径上工作,但是其他的东西都破了。

我的代码在下面

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


感谢您的帮助

当您使用CGTransform旋转UIBezier路径时,它将围绕点(0,0)旋转,对于您的路径,点(0,0)是形状的左上角。这就是为什么当你只是旋转90度而不做任何其他事情时,偏移是不正确的——它绕着错误的点旋转

因此,在旋转之前,需要将路径居中到点(0,0),然后旋转它,然后将其向后移动,以便(0,0)位于其左上角

以下代码将多边形旋转90度:

// 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)];
这将使多边形旋转90度,并使其左上角保持在(0,0)

蓝色轮廓是旋转之前的路径,绿色轮廓是旋转之后的路径:


亚当的回答有问题。沃尔夫在电话线上

[nonagon applyTransform:CGAffineTransformMakeTransform(nonagon.bounds.size.width/2,nonagon.bounds.size.height/2)]

它不会使多边形居中于帧的中心。应该是这样

//Centered version
[nonagon applyTransform:CGAffineTransformMakeTranslation(boundsForPoly.size.width/2, boundsForPoly.size.height/2/2)];
因此,代码应该与adam.wulf中的代码类似

// 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(boundsForPoly.size.width/2, boundsForPoly.size.height/2/2)];

180度变换?你不想要90度吗?对不起,是的,90度是正确的,但是偏移量都不正确,下面的图像不适合看。多谢各位