天天看點

iOS 擷取圓環終點位置的坐标方法 (UIBezierPath 終點位置)

目标是下圖的情況:

iOS 擷取圓環終點位置的坐标方法 (UIBezierPath 終點位置)

畫一個圓弧,在圓弧結束位置放置一個紅色圓點

這需要先假想一個坐标系效果如下

iOS 擷取圓環終點位置的坐标方法 (UIBezierPath 終點位置)

由于貝塞爾曲線是順時針方向繪制的,是以可以順時針想像成四個象限

擷取位置方法步驟:

1、确定所在的角度是多少

2、确定象限

3、後通正弦餘弦函數來确定x、y值

4、最終得出在整個layer 中的位置

具體算法

//更新小點的位置
-(CGRect)getEndPointFrameWithProgress:(float)progress
{
    CGFloat angle = M_PI*2.0*progress;//将進度轉換成弧度
    float radius = (_backView.bounds.size.width-_lineWidth)/2.0;//半徑
    int index = (angle)/M_PI_2;//使用者區分在第幾象限内
    float needAngle = angle - index*M_PI_2;//用于計算正弦/餘弦的角度
    float x = 0,y = 0;//用于儲存_dotView的frame
    switch (index) {
        case 0:
            NSLog(@"第一象限");
            x = radius + sinf(needAngle)*radius;
            y = radius - cosf(needAngle)*radius;
            break;
        case 1:
            NSLog(@"第二象限");
            x = radius + cosf(needAngle)*radius;
            y = radius + sinf(needAngle)*radius;
            break;
        case 2:
            NSLog(@"第三象限");
            x = radius - sinf(needAngle)*radius;
            y = radius + cosf(needAngle)*radius;
            break;
        case 3:
            NSLog(@"第四象限");
            x = radius - cosf(needAngle)*radius;
            y = radius - sinf(needAngle)*radius;
            break;
            
        default:
            break;
    }
    //為了讓圓圈的中心和圓環的中心重合
    x -= (_redDot.bounds.size.width/2.0f - _lineWidth/2.0f);
    y -= (_redDot.bounds.size.width/2.0f - _lineWidth/2.0f);
    //更新圓環的frame
    CGRect rect = _redDot.frame;
    rect.origin.x = x;
    rect.origin.y = y;
    return  rect;
}
           

☞  Demo