In computer graphics, the Liang–Barsky algorithm (named after You-Dong Liang and Brian A. Barsky) is a line clipping algorithm. The Liang–Barsky algorithm uses the parametric equation of a line and inequalities describing the range of the clipping window to determine the intersections between the line and the clip window. With these intersections it knows which portion of the line should be drawn. So this algorithm is significantly more efficient than Cohen–Sutherland. The idea of the Liang–Barsky clipping algorithm is to do as much testing as possible before computing line intersections.
The algorithm uses the parametric form of a straight line:
x=x0+t(x1-x0)=x0+t\Deltax,
y=y0+t(y1-y0)=y0+t\Deltay.
A point is in the clip window, if
xmin\lex0+t\Deltax\lexmax
ymin\ley0+t\Deltay\leymax,
tpi\leqi, i=1,2,3,4,
\begin{align} p1&=-\Deltax,&q1&=x0-xmin,&&(left)\\ p2&=\Deltax,&q2&=xmax-x0,&&(right)\\ p3&=-\Deltay,&q3&=y0-ymin,&&(bottom)\\ p4&=\Deltay,&q4&=ymax-y0.&&(top) \end{align}
To compute the final line segment:
pi=0
i
qi<0
pi<0
pi>0
pi
u=qi/pi
t
u1
u2
u1
pi<0
u1
\{0,qi/pi\}
u2
pi>0
u2
\{1,qi/pi\}
u1>u2
u1<0<1<u2
using namespace std;
// this function gives the maximumfloat maxi(float arr[],int n)
// this function gives the minimumfloat mini(float arr[], int n)
void liang_barsky_clipper(float xmin, float ymin, float xmax, float ymax, float x1, float y1, float x2, float y2)
int main
Algorithms used for the same purpose: