2014-06-15 45 views
2

我想繪製一個使用UIBezierPath和ZEPolygon的六角形,它的工作原理很棒,但是我的六邊形是平頂的。我嘗試了所有的方法,讓它在中間畫一個點,包括工作路徑上的180度轉換,但其他所有的東西都打破了。用UIBezierPath繪製六角形(點第一個)

This is how it looks now

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

感謝所有幫助

+1

180度變換下?你不想要90嗎? –

+0

對不起,90度是正確的,但偏移量都是不正確的,下面的圖像是沒有看到的地方 –

回答

1

當你旋轉UIBezierPath與CGTransf orm,它將圍繞點(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)

的藍色輪廓是你的路徑之前,和綠色的輪廓是旋轉後:

enter image description here

+0

太棒了。非常感謝 –

0

有來自adam.wulf我回答一個問題s同行

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