图形重绘有哪些用
当我们改变画图板时(如改变画图板尺寸大小时),会发现你绘制的图像在移动过程中消失了,这是为什么呢,我们又该如何解决这种问题呢?
首先,画图板的尺寸等都是我们设置好的,在改变其尺寸过程中,相当于重新设置了一个窗体,而这个过程中我们以前画的图形也会消失。为了使得我们画的图形不会消失,我们要记录下原来图形的基本数据,如立方体中点的坐标,边长等,然后在改变后再在新的窗体中绘制出来。
接下来,让我们通过正方体来认识这一过程,看看如何实现图形重绘。
图形重绘
一,创建一个类DrawUI来继承JFrame
public class DrawUI extends JFrame {//定义一个类
DrawListener dl = new DrawListener();//创建一个DrawListener对象
public void ShowUI() {//创建一个方法
setTitle("画画板");//命名
setSize(1000, 1000);//尺寸
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//默认关闭操作
FlowLayout fl = new FlowLayout();//创建流式布局操作
setLayout(fl);//在“jf”窗体中加入使用流式布局操作
二,创造一个类Myshape编写图形绘制所需要的构造方法
public class Myshape {
int x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x, y, w, h, d, c, dx, dy;
String shapeType;
Color color;
public Myshape(int x1, int y1, int x2, int y2, String shapeType, Color color) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.shapeType = shapeType;
this.color = color;
}//写入所需要储存的数据类型
public int abs(int a) {
if (a < 0) {
return -a;
}
return a;
}
public void drawshape(Graphics g) {
//根据保存的数据重绘图形
g.setColor(color);
if (shapeType.equals("直线")) {
g.drawLine(x1, y1, x2, y2);
} else if (shapeType.equals("矩形")) {
g.drawLine(x1, y1, x2, y1);
g.drawLine(x1, y1, x1, y2);
g.drawLine(x2, y1, x2, y2);
g.drawLine(x1, y2, x2, y2);
} else if (shapeType.equals("圆形")) {
g.drawOval(x1, y1, x2 - x1, y2 - y1);
} else if (shapeType.equals("实心圆形")) {
Color c = new Color(100, 100, 200);
g.setColor(c);
g.fillOval(x1, y1, x2 - x1, y2 - y1);
} else if (shapeType.equals("等腰三角形")) {
g.drawLine(x1, y2, x2, y2);
g.drawLine((x1 + x2) / 2, y1, x1, y2);
g.drawLine((x1 + x2) / 2, y1, x2, y2);
} else if (shapeType.equals("三角形")) {
if (c == 0) {
c++;
} else if (c == 1) {
c++;
g.drawLine(x3, y3, x4, y4);
} else if (c == 2) {
g.drawLine(x3, y3, x5, y5);
g.drawLine(x4, y4, x5, y5);
c = 0;
}
} else if (shapeType.equals("多边形")) {
if (c == 0) {
c++;
} else if (c == 1) {
c++;
g.drawLine(x3, y3, x4, y4);
} else if (c == 2) {
if (abs(x3 - x5) < 10 && abs(y3 - y5) < 10) {
g.drawLine(x3, y3, x4, y4);
c = 0;
return;
}
g.drawLine(x4, y4, x5, y5);
x4 = x5;
y4 = y5;
}
}
}
三,在DrawListener中创建数组保存所绘制的图形,创建数组下标
Myshape[] shapeList = new Myshape[200];
int index = 0;
四,创建数组,将图形保存到数组中(将获取到的数据进行保存)
@Override
public void mouseReleased(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
if (shapeType.equals("直线") || shapeType.equals("圆形")
|| shapeType.equals("等腰三角形") || shapeType.equals("矩形") || shapeType.equals("实心圆形")) {
Color color = null;
Myshape myShape = new Myshape(x1, y1, x2, y2, shapeType, color);//创造对象,保存数据
myShape.drawshape(g);
shapeList[index] = myShape;//将保存的数据保存在数组中
index++;
五,在DrawUI中使用paint方法来重绘图形
@Override
public void paint(Graphics g){
super.paint (g);
for(int i = 0; i < dl.index; i++){//遍历数组
Myshape shape = dl.shapeList[i];//取出图形对象
shape.drawshape (g);//调用绘制方法
}
}