При рисовании дуги с использованием CGContextAddArcToPoint (), что означают (x1, y1) и (x2, y2)? - PullRequest
17 голосов
/ 03 января 2012

Вы можете использовать следующий код, чтобы нарисовать дугу, используя Кварц:

CGContextMoveToPoint(context2, x, y);
CGContextAddArcToPoint(context2, x1, y1, x2, y2, r);

В этих функциях (x,y) является отправной точкой, а r является радиусом дуги, но что является (x1,y1)и (x2,y2)?

Ответы [ 4 ]

71 голосов
/ 25 сентября 2013

AddArcToPoint работает так:

ArcToPoint Diagram

, где P1 - это точка, в которой находится текущий путь, r - это radius, присвоенная функции, а красная линия - это линия, которую addArcToPoint добавит к текущему пути. Это не будет продолжаться до второй точки на x2, y2; оно остановится в конце дуги.

У меня есть запись в блоге об этом здесь .

10 голосов
/ 03 января 2012

http://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGContext/Reference/reference.html#//apple_ref/c/func/CGContextAddArcToPoint

x1: значение x в координатах пространства пользователя для конечной точки первой касательной линии. Первая касательная линия рисуется от текущей точки до (x1, y1).

y1: значение y в координатах пространства пользователя для конечной точки первой касательной линии. Первая касательная линия рисуется от текущей точки до (x1, y1).

x2: значение x в координатах пространства пользователя для конечной точки второй касательной линии. Вторая касательная линия рисуется из (x1, y1) в (x2, y2).

y2: значение y в координатах пространства пользователя для конечной точки второй касательной линии. Вторая касательная линия рисуется из (x1, y1) в (x2, y2).

6 голосов
/ 24 марта 2012

Вот код, который я только что построил, чтобы решить эту проблему, приближаясь к нему с точки зрения центра круга, с объявлениями и примерами значений:

CGPoint arcCenter = CGPointMake(30,20);
float arcLengthRad = M_PI_4; // Whatever, the full span of the arc in radians
float radius = 10;
float arcCenterRad = M_PI_2; // the angle of the center of the arc, in radians

float arcP1hyp = 1/cos(arcLengthRad/2) * radius;
float arcP1x = arcCenter.x + cosf(arcCenterRad)*arcP1hyp;
float arcP1y = arcCenter.y + sinf(arcCenterRad)*arcP1hyp;
float arcP2tx = arcCenter.x + cosf(arcCenterRad+(arcLengthRad/2))*radius;
float arcP2ty = arcCenter.y + sinf(arcCenterRad+(arcLengthRad/2))*radius;
float arcP2x = (arcP1x - arcP2tx)*-1 + arcP2tx;
float arcP2y = (arcP1y - arcP2ty)*-1 + arcP2ty;
CGContextAddArcToPoint(context, 
                       arcP1x, 
                       arcP1y,
                       arcP2x, 
                       arcP2y,
                       radius);

Таким образом, приведенный выше код должен создавать небольшую 45-градуснуюугловая дуга в верхней части круга.


Отредактировано: В ответ на полученный комментарий приведенный выше супер-краткий код показан ниже с комментариями и завернут вметод (плюс небольшая корректировка для вычисления arcP2)

/*
EOTContext:addArcWithCenter:arcLength:radius:arcMiddlePointAngle:

Use this method for building a circle with breaks at certain points, 
for example to use other CGContext methods to draw notches in the 
circle, or protruding points like gear teeth.

This method builds up the values to use in CGContextAddArcToPoint(), 
which are the x and y coordinates of two points.  First  added to 
the current point in context, form two lines that are the tangents of 
the entry and exit angles of the arc.

This method's arguments define the length of the arc in radians, and 
the position of start and end using the angle centerpoint of the arc.  
This is useful when drawing a certain defined amount of gear teeth, 
rotating around the circle.

It is beyond this method's scope to maintain or calculate the 
centerpoint relative to an arbitrary current point in the context, because this 
is primarily used for drawing a gear/notch circle.
*/
-(void)EOTContext:(CGContext*)context 
addArcWithCenter:(CGPoint)arcCenter 
arcLength:(CGFloat)arcLengthRad
radius:(CGFloat)radius
arcMiddlePointAngle:(CGFloat)arcCenterRad {



    /*
    Calculate the hypotenuse of the larger, outer circle where the 
    points of the tangent lines would rest upon (imagine wrapping 
    the drawn circle in a bounding regular convex polygon of tangent 
    lines, then wrap that polygon in an outer circle)
    */
    float arcP1hyp = 1/cos(arcLengthRad/2) * radius;

    // Build first tangent point
    CGPoint arcP1 = (CGPoint){
        arcCenter.x + cosf(arcCenterRad)*arcP1hyp,
        arcCenter.y + sinf(arcCenterRad)*arcP1hyp
    };

    // Build the final endpoint of the arc
    CGPoint arcP2final = (CGPoint){
        arcCenter.x + cosf(arcCenterRad+(arcLengthRad/2))*radius,
        arcCenter.y + sinf(arcCenterRad+(arcLengthRad/2))*radius
    };

    // Build second tangent point using the first tangent point and the final point of the arc.  
    // This point is resting on the bounding outer circle like arcP1 is.
    // This would also work using the final point itself, using the simple assignment of arcP2 = arcP2final;  
    //   or of course simply omitting arcP2 altogether.
    CGPoint arcP2 = (CGPoint){
        (arcP2final.x - arcP1.x) + arcP2final.x,
        (arcP2final.y - arcP1.y) + arcP2final.y
    };

    // The following adds an arc of a circle to the current path, using a radius and tangent points.
    CGContextAddArcToPoint(context, 
                           arcP1.x, 
                           arcP1.y,
                           arcP2.x, 
                           arcP2.y,
                           radius);
}
0 голосов
/ 12 ноября 2013

В документации Apple она кратко описана.

http://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGContext/Reference/reference.html#//apple_ref/c/func/CGContextAddArcToPoint

x1: значение x в координатах пространства пользователя для конечной точки первой касательной линии. Первая касательная линия рисуется от текущей точки до (x1, y1).

y1: значение y в координатах пространства пользователя для конечной точки первой касательной линии. Первая касательная линия рисуется от текущей точки до (x1, y1).

x2: значение x в координатах пространства пользователя для конечной точки второй касательной. Вторая касательная линия рисуется из (x1, y1) в (x2, y2).

y2: значение y в координатах пространства пользователя для конечной точки второй касательной линии. Вторая касательная линия рисуется из (x1, y1) в (x2, y2).

...