Tuesday, March 31, 2009

Dashed line drawing in java graphics.


Hello Friends,

 While working in my project i was searching how to draw a dashed line
in Graphics not in Graphics2D.

So i get this code and it is superb for drawing dash lines or rectangulars.
Just pass the line points and assign your dash length and space length.
See the below function........

////pass the line point x1,y1 and point 2 as x2 and y2
public void drawDashedLine(Graphics g, int x1, int y1, int x2,
                                                   int y2, double dash_length, double space_length)
{
          ///if both the points are same
          if ((x1 == x2) && (y1 == y2))
          {
                   g.drawLine(x1, y1, x2, y2);
                   return;
          }

          ///calculating line length
          double linelength = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));

          double yincrement = (y2 - y1) / (linelength / (dash_length + space_length));
          double xincdashspace = (x2 - x1) / (linelength / (dash_length + space_length));
          double yincdashspace = (y2 - y1) / (linelength / (dash_length + space_length));
          double xincdash = (x2 - x1) / (linelength / (dash_length));
          double yincdash = (y2 - y1) / (linelength / (dash_length));
          int counter = 0;
          for (double i = 0; i < linelength - dash_length; i += dash_length + space_length)
          {
                   g.drawLine((int)(x1 + xincdashspace * counter),
                               (int)(y1 + yincdashspace * counter),
                               (int)(x1 + xincdashspace * counter + xincdash),
                                (int)(y1 + yincdashspace * counter + yincdash));
                   counter++;
          }

          if ((dashlength + spacelength) * counter <= linelength)
                   g.drawLine((int)(x1 + xincdashspace * counter),
                               (int)(y1 + yincdashspace * counter), x2, y2);
}
=============================================

No comments:

Post a Comment