Java图形设计中,利用Bresenham算法实现直线线型,线宽的控制(NO 2D GRAPHICS)

类别:Java 点击:0 评论:0 推荐:

Java 2D Graphics提供了强大的画线功能,可以控制线型,线宽,刷子的形状等,但在JDK1.2以前,没有提供这样一个功能,为了保持与旧版JDK的相容,实现一个可控制线型,线宽的画直线方法还是有必要的,下面是我写的一个静态方法,可直接用来画各种类型的直线:

/**
 * Bresenham Line Algorithm
 * @author Turbo Chen
 * @version 1.0 copyright 2001
 * @email [email protected]
 * @param dashedMask 设置线型的虚线的间隔,为0则画实线。
 * @param lineWidth 设置线宽。
 * @param x1 
 * @param y1
 * @param x2
 * @param y2
*/

public static void bresenhamLine(java.awt.Graphics g, int dashedMask, int lineWidth, int x1, int y1, int x2, int y2)
    {
        int  x, y;
        int  dx, dy;
        int  incx, incy;
        int  balance;
        int i=0;
        if (x2 >= x1)
        {
            dx = x2 - x1;
            incx = 1;
        }
        else
        {
            dx = x1 - x2;
            incx = -1;
        }

        if (y2 >= y1)
        {
            dy = y2 - y1;
            incy = 1;
        }
        else
        {
            dy = y1 - y2;
            incy = -1;
        }

        x = x1;
        y = y1;

        if (dx >= dy)
        {
            dy <<= 1;
            balance = dy - dx;
            dx <<= 1;

            while (x != x2)
            {
                if ( (i & dashedMask)==0 )
                g.fillOval(x, y,lineWidth,lineWidth);
                if (balance >= 0)
                {
                    y += incy;
                    balance -= dx;
                }
                balance += dy;
                x += incx;
                i ++;
            }
            if ( (i & dashedMask)==0 )
                g.fillOval(x, y,lineWidth,lineWidth);
        }
        else
        {
            dx <<= 1;
            balance = dx - dy;
            dy <<= 1;

            while (y != y2)
            {
                if ( (i & dashedMask)==0 )
                g.fillOval(x, y,lineWidth,lineWidth);
                if (balance >= 0)
                {
                    x += incx;
                    balance -= dy;
                }
                balance += dx;
                y += incy;
                i ++;
            }
            if ( (i & dashedMask)==0 )
                g.fillOval(x, y,lineWidth,lineWidth);
        }
    }

大家注意看程序中的g.fillOval()方法,也就是说我是用画圆点的方式来画线的,即刷子的样式是圆头型,你可以很容易的改变成g.fillRect()等其它方式,来实现刷子样式的设置.

 

本文地址:http://com.8s8s.com/it/it18322.htm