Quad / Bezier min / max search with CoreGraphics

I use CoreGraphics to draw a quadratic bezier, but I want to calculate the minimum / maximum value of the curve. I'm not from a mathematical background, so it got a little troublesome. Does anyone have any articles or ideas on how to solve this?

+5
source share
3 answers

For quadratic Bezier, this is actually quite simple.

Define the three control points as P0 = (x0,y0), P1 = (x1,y1)and P2 = (x2,y2). To find the extrema in x, solve this equation:

t = (x0 - x1) / (x0 - 2*x1 + x2)

If 0 <= t <= 1, then evaluate your curve in tand save it as Px. Do the same for y:

t = (y0 - y1) / (y0 - 2*y1 + y2)

, 0 <= t <= 1, t Py. , , P0, P2, Px ( ) Py ( ). .

+3

javascript:

Jsfiddle

function P(x,y){this.x = x;this.y = y; }
function pointOnCurve(P1,P2,P3,t){
    if(t<=0 || 1<=t || isNaN(t))return false;
    var c1 =  new P(P1.x+(P2.x-P1.x)*t,P1.y+(P2.y-P1.y)*t);
    var c2 =  new P(P2.x+(P3.x-P2.x)*t,P2.y+(P3.y-P2.y)*t);
    return new P(c1.x+(c2.x-c1.x)*t,c1.y+(c2.y-c1.y)*t);  
}
function getQCurveBounds(ax, ay, bx, by, cx, cy){
    var  P1 = new P(ax,ay);
    var  P2 = new P(bx,by);
    var  P3 = new P(cx,cy);
    var tx =  (P1.x - P2.x) / (P1.x - 2*P2.x + P3.x);
    var ty =  (P1.y - P2.y) / (P1.y - 2*P2.y + P3.y);
    var Ex = pointOnCurve(P1,P2,P3,tx);
    var xMin = Ex?Math.min(P1.x,P3.x,Ex.x):Math.min(P1.x,P3.x);
    var xMax = Ex?Math.max(P1.x,P3.x,Ex.x):Math.max(P1.x,P3.x);
    var Ey = pointOnCurve(P1,P2,P3,ty);
    var yMin = Ey?Math.min(P1.y,P3.y,Ey.y):Math.min(P1.y,P3.y);
    var yMax = Ey?Math.max(P1.y,P3.y,Ey.y):Math.max(P1.y,P3.y);
    return {x:xMin, y:yMin, width:xMax-xMin, height:yMax-yMin};
}
+1

All Articles