有一个JPanel
我使用a绘制地图的图像BufferedImage
。我还有一个按钮,当点击它时,将通过在该部分上绘制一个红色矩形来突出显示地图的一部分。
但是,当我放大图像时,矩形会保持原样。我假设背后的原因是矩形正在面板上和图像上绘制。
有没有办法根据变焦调整矩形的位置?
这是我绘制矩形和图像的方式:
//the variable years[activeIndex] is an array which stores my Buffered Images
Graphics2D g2=(Graphics2D)g.create();
g.drawImage( years[activeIndex],0, 0,(int)width,(int)height,null);
g2.setColor(Color.red);
g2.setStroke(new BasicStroke(3));
g2.drawRect(this.getWidth()/2,this.getHeight()/2, 20, 20);
MapViewer.imagePanel.revalidate();
发布于 2018-09-19 13:47:23
有一个特殊的变换,如果我理解正确,你调整图像大小,然后将它放在JPanel的(0,0) - 这个问题可以通过找到仿射变换来解决,但更简单
在下面的程序中,我有一个JFrame和一个矩形r。过程如下:
translate the center of the rectangle to come to (0, 0)
scale the rectangle accordingly
retranslate the center back with the new dimensions
public void zoom(int z) {
int newW=getWidth()*z, newH=getHeight()*z;
int rcx=r.x+r.width/2, rcy=r.y+r.height/2; // center of rectangle
int newx=rcx-b.getWidth()/2, newy=rcy-b.getHeight()/2; // move to (0, 0)
newx*=z; newy*=z; // scale
newx+=newW/2; newy+=newH/2; // retranslate back
setSize(newW, newH);
b=new BufferedImage(newW, newH, BufferedImage.TYPE_INT_RGB);
Graphics2D g=(Graphics2D)b.getGraphics();
g.drawImage(b2, 0, 0, newW, newH, null);
r.x=newx-r.width/2; r.y=newy-r.height/2; // only change the position not the scale
repaint();
}
public void paint(Graphics g) {
g.drawImage(b, 0, 0, null);
g.setColor(Color.black);
((Graphics2D)g).draw(r);
}
https://stackoverflow.com/questions/-100006142
复制相似问题