如何使用“*”绘制线条线

时间:2011-11-15 23:39:02

标签: java

我想在控制台中使用“*”绘制一条线,但我只得到2“*”。我认为线算法有问题。也许有一种更简单的方法。

Class MyGraphics:

 class MyGraphics {
int x, y;
private int width, height;
MyGraphics(int wid, int hit) {

    fb= new FrameBuffer(wid,hit);
    width = fb.getWidth();
    height = fb.getHeight();
}
MyGraphics() {
    fb = new FrameBuffer();
    width = fb.getWidth();
    height = fb.getHeight();
}

void drawLine(int x1,int y1,int x2,int y2)
{
 width= x2 - x ;
height = y2 - y ;
   int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0 ;
    if (width<0) dx1 = -1 ; else if (width>0) dx1 = 1 ;
   if (height<0) dy1 = -1 ; else if (height>0) dy1 = 1 ;
   if (width<0) dx2 = -1 ; else if (width>0) dx2 = 1 ;
   int longest = Math.abs(width) ;
   int shortest = Math.abs(height) ;
  if (!(longest>shortest)) {
    longest = Math.abs(height) ;
    shortest = Math.abs(width) ;
    if (height<0) dy2 = -1 ; else if (height>0) dy2 = 1 ;
    dx2 = 0 ;
}
int numerator = longest >> 1 ;
for (int i=0;i<=longest;i++) {
    fb.setPixel(x1, y1);

    numerator += shortest ;
    if (!(numerator<longest)) {
        numerator -= longest ;
        x += dx1 ;
        y += dy1 ;
    } else {
        x += dx2 ;
        y += dy2 ;
    }
}
return;
}
void display() {
    fb.display();
    return;
    } // simply calls the frame buffer's display method

FrameBuffer fb;
}



/*void drawLine(int x1,int y1,int x2,int y2)
{
width= x2 - x ;
height = y2 - y ;
int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0 ;
if (width<0) dx1 = -1 ; else if (width>0) dx1 = 1 ;
if (height<0) dy1 = -1 ; else if (height>0) dy1 = 1 ;
if (width<0) dx2 = -1 ; else if (width>0) dx2 = 1 ;
int longest = Math.abs(width) ;
int shortest = Math.abs(height) ;
if (!(longest>shortest)) {
    longest = Math.abs(height) ;
    shortest = Math.abs(width) ;
    if (height<0) dy2 = -1 ; else if (height>0) dy2 = 1 ;
    dx2 = 0 ;
}
int numerator = longest >> 1 ;
for (int i=0;i<=longest;i++) {
    fb.setPixel(y, x);

    numerator += shortest ;
    if (!(numerator<longest)) {
        numerator -= longest ;
        x += dx1 ;
        y += dy1 ;
    } else {
        x += dx2 ;
        y += dy2 ;
    }
}
return;
}*/

Class MyGraphicsApp:

class MyGraphicsApp {
MyGraphicsApp() {mg = new MyGraphics(80, 25);}

void paint(MyGraphics g) {
    g.drawLine(5, 12, 27, 2);
    g.drawLine(2, 2, 30, 30);
}

void repaint() {
    paint(mg);
    mg.display();
}

public static void main(String [] args) {
    MyGraphicsApp myGraphicsApp = new MyGraphicsApp();
    myGraphicsApp.repaint();
}

MyGraphics mg;
}

1 个答案:

答案 0 :(得分:0)

我怀疑这个作业

width= x2 - x ;
height = y2 - y ;

应该是

width= x2 - x1 ;
height = y2 - y1 ;

这条线也错了

fb.setPixel(x1, y1);

因为您永远不会更改x1y1的值。