Java Graphics2D 平移和缩放/平移和缩放
我有一个正在绘制的 JPanel,并且正在尝试获取它,以便您可以使用鼠标滚轮通过修改变量比例来“放大”和缩小。现在发生的情况是,您可以放大或缩小,但当您放大时,所有绘图都会向右和向下移动,而在缩小时会向上和向左移动。
我想让它像放大 JPanel 中心的点一样进行调整,但我不知道如何计算要平移的正确偏移量……
任何人都知道如何做到这一点,或者甚至更好的更干净的方式来实现整个平移和缩放功能?
我基本上绘制了来自系统的一堆坐标,其中 0,0 位于左下角并落在边界之间:
xMin = 661208
xMax = 662618
yMin = 4291657
yMax = 4293285
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
double scale = details.getScale();
double xOffset = details.getxOffset();
double yOffset = details.getyOffset();
g2.scale(scale, -scale);
// Dividing offset by scale makes panning 1:1 with the cursor still. yMax to account for the
// fact we needed to flip around the y axis to make it right-side up.
g2.translate((-xMin + xOffset / scale), (-yMax + yOffset / scale));
// Code to draw stuff goes here. It uses coordinates between xMin-xMax and yMin-yMax to draw.
.
.
.
}
I've got a JPanel I'm drawing onto and I'm trying to get it so that you can use the mouse wheel to "zoom" in and out by modifying the variable scale. Right now what happens is you can zoom in or out but all of the drawing shifts to the right and downwards when you zoom in and then back up and left when zooming out.
I want to make it so that it adjusts as if you were zooming in on the point at the center of the JPanel but I can't figure out how to calculate the right offset to translate by…
Anybody got an idea of how to do this, or even better a cleaner way of achieving this whole pan and zoom ability?
I am basically plotting a bunch of coordinates that came from a system where 0,0 is in the lower left corner and fall between the bounds:
xMin = 661208
xMax = 662618
yMin = 4291657
yMax = 4293285
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
double scale = details.getScale();
double xOffset = details.getxOffset();
double yOffset = details.getyOffset();
g2.scale(scale, -scale);
// Dividing offset by scale makes panning 1:1 with the cursor still. yMax to account for the
// fact we needed to flip around the y axis to make it right-side up.
g2.translate((-xMin + xOffset / scale), (-yMax + yOffset / scale));
// Code to draw stuff goes here. It uses coordinates between xMin-xMax and yMin-yMax to draw.
.
.
.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个带有轮子的示例:
Here is an example with the wheel: