我正在尝试使用 AffineTransform 从其中心缩放一个矩形。我确信解决方案是显而易见的,但我无法让它发挥作用!这是我到目前为止测试过的...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Test extends JPanel {
Test()
{
super(null);
setOpaque(true);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(200,200));
}
@Override
protected void paintComponent(Graphics g1) {
super.paintComponent(g1);
Rectangle r= new Rectangle(5,5,getWidth()-10,getHeight()-10);
double cx= r.getCenterX();
double cy= r.getCenterY();
Graphics2D g=(Graphics2D)g1;
g.setColor(Color.BLACK);
AffineTransform old= g.getTransform();
for(double zoom=0.9; zoom>=0.5; zoom-=0.1)
{
AffineTransform tr2= new AffineTransform(old);
tr2.translate(-cx, -cy);
tr2.scale(zoom, zoom);
tr2.translate(cx/zoom,cy/zoom);
g.setTransform(tr2);
g.draw(r);
g.setTransform(old);
}
}
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, new Test());
}
}
但它不起作用....有什么建议吗?