Ardoise.java
3.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package tp2.ArdoiseMagique;
import javax.swing.*;
import java.awt.*;
public class Ardoise extends JPanel {
private final int defaultWidth = 1000;
private final int defaultHeight = 600;
protected static final int BLACK = 1;
protected static final int WHITE = 0;
private int oldx = -1;
private int oldy = -1;
private final int[][] pixelArray = new int[defaultWidth][defaultHeight];
public Ardoise() {
super();
this.setSize(defaultWidth, defaultHeight);
wipe();
}
public void wipe() {
for (int i = 0; i < defaultWidth; ++i){
for (int j = 0; j < defaultHeight; ++j){
pixelArray[i][j] = WHITE;
}
}
repaint();
}
public void setPixel(int x, int y, int color){
if (x < 0 || y < 0 || x >= defaultWidth || y >= defaultHeight){
return;
}
if (oldx == -1 || oldy == -1){
oldx = x;
oldy = y;
}
plotLine(oldx, oldy, x, y);
oldx = x;
oldy = y;
pixelArray[x][y] = color;
repaint();
}
public void plotLineLow(int x0, int y0, int x1, int y1){
int dx = x1 - x0;
int dy = y1 - y0;
int yi = 1;
if (dy < 0) {
yi = -1;
dy = -dy;
}
int D = (2 * dy) - dx;
int ay = y0;
for (int ax = x0; ax < x1; ++ax) {
pixelArray[ax][ay] = BLACK;
if (D > 0) {
ay = ay + yi;
D = D + (2 * (dy - dx));
} else D = D + 2 * dy;
}
}
public void plotLineHigh(int x0, int y0, int x1, int y1){
int dx = x1 - x0;
int dy = y1 - y0;
int xi = 1;
if (dx < 0) {
xi = -1;
dx = -dx;
}
int D = (2 * dx) - dy;
int ax = x0;
for (int ay = y0; ay < y1; ++ay) {
pixelArray[ax][ay] = BLACK;
if (D > 0) {
ax = ax + xi;
D = D + (2 * (dx - dy));
} else D = D + 2 * dx;
}
}
public void plotLine(int x0, int y0, int x1, int y1) {
if (Math.abs(y1 - y0) < Math.abs(x1 - x0)) {
if (x0 > x1) {
plotLineLow(x1, y1, x0, y0);
} else {
plotLineLow(x0, y0, x1, y1);
}
} else {
if (y0 > y1) {
plotLineHigh(x1, y1, x0, y0);
} else {
plotLineHigh(x0, y0, x1, y1);
}
}
}
public void resetOld() {
oldx = -1;
oldy = -1;
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.WHITE);
for (int i = 0; i < defaultWidth; ++i){
for (int j = 0; j < defaultHeight; ++j){
/*
since most of the image will be white and few pixels will be black,
we set the color to white and when we encounter a black pixel,
we temporarily change the color to black, paint the pixel and switch
it back to white.
*/
if (pixelArray[i][j] == BLACK){
g.setColor(Color.BLACK);
g.drawLine(i, j, i, j);
g.setColor(Color.WHITE);
} else if (pixelArray[i][j] == WHITE){
g.drawLine(i, j, i, j);
}
}
}
}
}