我正在尝试使用UIBezierPath和ZEPolygon绘制六边形,它效果很好,但我的六边形是平顶的。我已经尝试了所有的东西,让它在中间绘制一个点,包括在路径上的180度变换,但是其他一切都会破坏。
This is how i would like it to look
我的代码在
下面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
感谢您的帮助
答案 0 :(得分:1)
当您使用CGTransform旋转UIBezierPath时,它将围绕点(0,0)旋转,对于您的路径,点(0,0)是您的形状的左上角。这就是为什么当你只旋转90度w / o做其他事情时偏移是不正确的 - 它绕着错误的点旋转。
因此,在旋转之前,需要将路径居中到点(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)
蓝色轮廓是之前的路径,绿色轮廓是旋转之后:
答案 1 :(得分: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)];