首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在缓冲图像Java上绘制矩形?

如何在缓冲图像Java上绘制矩形?
EN

Stack Overflow用户
提问于 2018-09-19 04:26:24
回答 1查看 0关注 0票数 0

有一个JPanel我使用a绘制地图的图像BufferedImage。我还有一个按钮,当点击它时,将通过在该部分上绘制一个红色矩形来突出显示地图的一部分。

但是,当我放大图像时,矩形会保持原样。我假设背后的原因是矩形正在面板上和图像上绘制。

有没有办法根据变焦调整矩形的位置?

这是我绘制矩形和图像的方式:

代码语言:javascript
复制
//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();
EN

回答 1

Stack Overflow用户

发布于 2018-09-19 13:47:23

有一个特殊的变换,如果我理解正确,你调整图像大小,然后将它放在JPanel的(0,0) - 这个问题可以通过找到仿射变换来解决,但更简单

  • 你缩放图像
  • 并将其翻译为适合JPanel

在下面的程序中,我有一个JFrame和一个矩形r。过程如下:

代码语言:javascript
复制
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);
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100006142

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档