The Java Program: Image.java
1 public final class Image {
2
3 final int width, height;
4 private final Color[][] buffer;
5
6 Image (int w, int h) {
7 width = w; height = h;
8 buffer = new Color[height][width];
9 clear();
10 }
11
12 void clear () {
13 for (int row=0; row<height; row++) {
14 for (int col=0; col<width; col++) {
15 buffer[row][col] = Color.white;
16 }
17 }
18 }
19
20 void display () {
21 for (int row=0; row<height; row++) {
22 System.out.format ("%2d:", row);
23 for (int col=0; col<width; col++) {
24 System.out.print (buffer[row][col]);
25 }
26 System.out.println ();
27 }
28 }
29
30 void setPixel (int x, int y) { setPixel (x,y,Color.black); }
31 void setPixel (int x, int y, Color c) { buffer[y][x] = c; }
32
33 void drawRect (int xP, int yP, int xQ, int yQ, Color color) {
34 for (int x=xP; x<xQ; x++) {
35 setPixel (x, yP, color); setPixel (x, yQ-1, color);
36 }
37 for (int y=yP; y<yQ; y++) {
38 setPixel (xP, y, color); setPixel (xQ-1, y, color);
39 }
40 }
41
42 void drawLine (int xP, int yP, int xQ, int yQ) {
43 drawLine (xP, yP, xQ, yQ, Color.black);
44 }
45
46
47 void drawLine (int xP, int yP, int xQ, int yQ, Color color) {
48
49 final int HX, HY, xInc, yInc;
50 if (xP > xQ){xInc= -1; HX = xP-xQ;} else {xInc=1; HX = xQ-xP;}
51 if (yP > yQ){yInc= -1; HY = yP-yQ;} else {yInc=1; HY = yQ-yP;}
52
53 int x = xP, y = yP, D = 0;
54
55 if (HY <= HX) {
56 final int c = 2*HX;
57 final int M = 2*HY;
58 for (;;) {
59 setPixel (x, y, color);
60 if (x == xQ) break;
61 x += xInc;
62 D += M;
63 if (D > HX) {y += yInc; D -= c;}
64 }
65 } else {
66 final int c = 2*HY;
67 final int M = 2*HX;
68 for (;;) {
69 setPixel (x, y, color);
70 if (y == yQ) break;
71 y += yInc;
72 D += M;
73 if (D > HY) {x += xInc; D -= c;}
74 }
75 }
76 }
77
78 public static void main (final String[] args) {
79 final Image i = new Image (20,13);
80 i.drawRect (0, 0, 20, 13, Color.grey (0.1));
81 i.drawLine (0, 0, Integer.parseInt (args[0]),Integer.parseInt (args[1]));
82 i.display();
83 }
84 }