[英]How to draw polygons in cocoa touch using UIBezierPath
I want to draw polygon of different sides (4-12). 我想绘制不同边的多边形(4-12)。 What is the logic for drawing a polygon.
绘制多边形的逻辑是什么? For eg if user selects 6 side, it should draw a hexagon, if user enters 8 sides it should draw a octagon.
例如,如果用户选择6个边,则应绘制一个六边形;如果用户输入8个边,则应绘制一个八边形。 I have found the following code but i also want to resize the UIView in which i am drawing a polygon so that the shape inside of the view also grows along with the view.
我找到了以下代码,但我也想调整UIView的大小,在其中绘制多边形,以便视图内部的形状也随视图一起增长。 Any body can help me please.
任何人都可以帮助我。 Following is the code i am using currently but it is not positioned at the center also when i resize the view that shape moves to another position in the view.
以下是我当前正在使用的代码,但是当我调整视图的大小以使形状移动到视图中的另一个位置时,它也不位于中心。
int radius = MINIMUM(widht, height)*0.4 ;
for (int i = 0; i < _numberOFsides; i++){
CGPoint point = CGPointMake(widht/2+radius *cosf(i*2*M_PI/_numberOFsides), widht/2+radius*sinf(i*2*M_PI/_numberOFsides));
if (i==0) {
[_shapePath moveToPoint:point];
}
else{
[_shapePath addLineToPoint:point];
[_shapePath stroke];
}
}
now to resize ur UIBazierPath you can add below code, 现在要调整您的UIBazierPath的大小,您可以添加以下代码,
CGRect bazierRect = CGPathGetBoundingBox(bezierpath.CGPath)
CGFloat scaleX = view.frame.size.width / bazierRect.frame.size.width;
CGFloat scaleY = view.frame.size.height / bazierRect.frame.size.height;
CGAffineTransform transform = CGAffineTransformMakeScale(scaleX, scaleY);
CGPathRef newPath = CGPathCreateCopyByTransformingPath(bezierpath.CGPath, &transform);
bezierPath.CGPath = newPath;
CFRelease(newPath);
If you want to make a regular polygon with any number of sides the following code will give you the vertices of each edge and it is easy to rescale in size and number of sides: 如果要制作具有任意多个边的规则多边形,以下代码将为您提供每个边的顶点,并且很容易重新调整大小和边数:
int n = 10; //number of edges
float j = 20; //length of each edge
float x = 130;
float y = 250;//the point 130,250 will be at the bottom of the figure
float angle = 2*M_PI;
for (int i = 0; i < n; i++) {
CGRect frame = CGRectMake(x, y, 2, 2);//put a dot on x,y
NSLog(@"%f | %f, %f", angle, x, y);
x = x + j*cosf(angle);
y = y + j*sinf(angle); //move to the next point
angle = angle - 2*M_PI/n; //update the angle
//display the dot
UIView *rect = [[UIView alloc] initWithFrame:frame];
rect.backgroundColor = [UIColor blueColor];
[self.view addSubview:rect];
}
Hope this helps. 希望这可以帮助。 If you have any questions feel free to ask and have a great day!
如果您有任何疑问,请随时提出并祝您愉快!
~Deadly Porcupine 〜致命豪猪
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.