使用UIBezierPath(先定义点)绘制六边形

3
我正在尝试使用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];

这是我用来绘制贝塞尔路径的库

非常感谢您的帮助


1
180度的转换?你不是想要90度吗? - Mick MacCallum
抱歉,是的,90度是正确的,但偏移量都不正确,下面的图像也无法看到。 - Jonathan Ogle-Barrington
2个回答

1
当你使用CGTransform旋转UIBezierPath时,它会围绕点(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)处。

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

enter image description here


太棒了。非常感谢。 - Jonathan Ogle-Barrington

0

adam.wulf 的答案存在问题,与以下代码行有关:

[nonagon applyTransform:CGAffineTransformMakeTranslation(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)];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接