我尝试在Java中创建DDA线条绘制算法的实现。我创建了JFrame表单和dda.java类。此时此刻,JFrame上只有一个按钮操作。我不确定在JFrame类中实现DDA。我认为drawPixel方法可能有问题,但我根本不确定JFrame的实现。我感谢你的评论。
这是dda.java中的划线方法
void drawLineDDA(Graphics2D g) {
dx=(double)(x2-x1);
dy=(double)(y2-y1);
double m=Math.abs(dy/dx);
double absx=Math.abs(dx);
double absy=Math.abs(dy);
double px = absx/p;
double py = absy/p;
int p=0;
float slope = 1;
if(y1==y2){
if(x1==x2) return; //it is not a line, nothing happened
slope = 0;
absx = 1;
absy = 0;
p=(int) (dx/absx); //p means number of steps
}
else if(x1==x2){
slope = 2;
absx = 0;
absy = 1;
p = (int) (dy/absy);
}
else{
slope = (float) (dy/dx);
absx=1;
absy=slope*absx;
p= (int) ((dy/absy > dx/absx) ? dy/absy : dx/absx);
}
for(int i = 0; i <=p;i++){
drawPixel(x1,y1,Color.BLACK);
x1 += absx;
y1 += absy;
}}
方法在dda.java绘制像素
private void drawPixel(int x1, int y1, Color BLACK) {
g.drawOval(x1, y1, x1+5, y1+5); //can be mistake right here?
}
JFrame类的一部分
public class NewJFrame extends javax.swing.JFrame {
int x1,x2,y1,y2;
Graphics2D g;
dda d;
public NewJFrame() {
this.d = new dda(20,30,20,50); //maybe this is not good?
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
g = (Graphics2D) jPanel1.getGraphics();
d.drawLineDDA(g); // and I am definielly not sure about this
}
您不应该将getGraphics()
用于自定义绘制,因为它是一个临时缓冲区,在下次重新绘制时会回收。你用paintComponent()
画画吗。覆盖JComponent
或JPanel
的paintComponent()
方法。有关详细信息和示例,请参见执行自定义绘制。另请参见AWT和Swing中的绘画。
drawPixel
方法也存在一个问题,因为椭圆的尺寸取决于坐标。尝试使用常量维度。CCD_ 7可能更适合。这里有一个例子:
private void drawPixel(Graphics2D g, int x1, int y1) {
g.fillOval(x1, y1, 3, 3);
}