AffineTransform:从其中心缩放一个Shape [英] AffineTransform: scaling a Shape from its center
本文介绍了AffineTransform:从其中心缩放一个Shape的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用AffineTransform从其中心缩放一个矩形。我确信解决方案很明显,但我无法完成它!这是我迄今为止测试过的内容...
I'm trying to scale a rectangle from its center using AffineTransform. I'm sure the solution is obvious but I cannot make it work ! Here is what I've tested so far...
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());
}
}
但它不起作用....任何建议?
But it doesn't work.... Any suggestion ?
推荐答案
我明白你在处理矩形时的意思。原因是翻译的初始计算没有考虑到容器对象的大小。
I see what you mean when you're dealing with rectangles. The reason is because the initial calculation for the translation didn't take into account the size of the container object.
使用这个代替:
tr2.translate(
(this.getWidth()/2) - (r.getWidth()*(zoom))/2,
(this.getHeight()/2) - (r.getHeight()*(zoom))/2
);
tr2.scale(zoom,zoom);
g.setTransform(tr2);
在缩放之前,将矩形转换为面板的中心。在我的测试中,它工作得很好。
What this is doing is translating the rectangle to the center of the panel before scaling it. In my tests it works just fine.
这篇关于AffineTransform:从其中心缩放一个Shape的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文