java仿射转换不同的图形对象
我用这个方法调用draw类:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
DrawGradient gradient = new DrawGradient();
gradient.draw(g);
DrawCoordinateSystem coor = new DrawCoordinateSystem();
coor.draw(g);
}
我试图转换DrawGradient类中的对象,但由于某种原因,DrawCoordinateSystem类中的图形对象被转换。为什么
DrawCoordinateSystem类:
public class DrawCoordinateSystem {
public DrawCoordinateSystem() {
// TODO Auto-generated constructor stub
}
public void draw(Graphics g1){
Color customcolor = new Color(210,191,245);
int x0 = 15, y0 = 15;
int Xpoints[] = {x0+45, x0+40, x0+40};
int Ypoints[] = {y0, y0-5, y0+5};
int Xpoints1[] = {x0, x0+5, x0-5};
int Ypoints1[] = {y0+45, y0+40, y0+40};
g1.setColor(customcolor);
g1.drawPolygon(Xpoints,Ypoints, 3);
g1.fillPolygon(Xpoints,Ypoints, 3);
g1.drawPolygon(Xpoints1,Ypoints1, 3);
g1.fillPolygon(Xpoints1,Ypoints1, 3);
g1.drawLine(x0, y0, x0+40, y0);
g1.drawLine(x0, y0, x0, y0+40);
g1.setFont(new Font("TimesRoman", Font.PLAIN, 12));
g1.drawString("x", 52, 30);
g1.setFont(new Font("TimesRoman", Font.PLAIN, 12));
g1.drawString("y", 23, 57);
}
}
渐变类:
public class DrawGradient {
public DrawGradient() {
}
private Color c1;
private Color c2;
public void draw( Graphics g ) {
Graphics2D g2d1 = (Graphics2D) g;
GradientPaint gp = new GradientPaint(0, 0, c2, 0, 100, c1);
g2d1.setPaint(gp);
Rectangle reckt = new Rectangle(0,0,100,100);
g2d1.fill(reckt);
AffineTransform move = new AffineTransform();
move.translate(200, 200);
g2d1.setTransform(move);
}
}
# 1 楼答案
转换是复合的,所以,一旦你应用了一个转换,你需要在完成时反转它
现在,您可以手动执行此操作,也可以在创建
Graphics
上下文之前创建一个副本,并在完成后将其处理掉。这样可以防止对副本的属性所做的任何更改被更改为对原始副本的更改(但您绘制的内容仍然保留)例如,在您的情况下,我需要先创建
Graphics
上下文的副本,然后再将其传递给其他方法这样你就能控制局面。如果可以避免的话,我建议不要在
paintComponent
方法中创建新对象,尤其是如果这些对象没有从一个绘制周期切换到另一个绘制周期,因为paintComponent
可以快速连续调用多次