簡體   English   中英

如何使用UIBezierPath在可可觸摸中繪制多邊形

[英]How to draw polygons in cocoa touch using UIBezierPath

我想繪制不同邊的多邊形(4-12)。 繪制多邊形的邏輯是什么? 例如,如果用戶選擇6個邊,則應繪制一個六邊形;如果用戶輸入8個邊,則應繪制一個八邊形。 我找到了以下代碼,但我也想調整UIView的大小,在其中繪制多邊形,以便視圖內部的形狀也隨視圖一起增長。 任何人都可以幫助我。 以下是我當前正在使用的代碼,但是當我調整視圖的大小以使形狀移動到視圖中的另一個位置時,它也不位於中心。

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

        }

現在要調整您的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);

如果要制作具有任意多個邊的規則多邊形,以下代碼將為您提供每個邊的頂點,並且很容易重新調整大小和邊數:

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

希望這可以幫助。 如果您有任何疑問,請隨時提出並祝您愉快!

〜致命豪豬

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM