放大并缩小java?

时间:2016-03-29 09:30:47

标签: java swing graphics

我是java的新手,如果它有任何含糊之处,那么请正确地回答我的问题。

我的代码放大和缩小正在工作。但是我面临的问题是当zoom_In完成时,在超过图像的缓冲图像上绘制线条。 假设在图像边缘绘制一条线,如果缩放百分比稍微改变,则会离开图像。比如.2或.3%。

在此发布我的代码,以便更好地了解我目前面临的问题。看看吧。

public class PictureBox extends JPanel {

Graphics2D graphics2D;
static BufferedImage image;
private double zoom = 1.0;
private double percentage = .1;
int width = 0,height = 0;

public PictureBox(){
    setDoubleBuffered(false);
    this.setBorder(UIManager.getBorder("ComboBox.border"));
    this.repaint();     
}

@Override
public void paintComponent(Graphics g){

    super.paintComponent(g);    
    if(image == null){
        image = new BufferedImage(GlobalConstant.imageSize, GlobalConstant.imageSize, BufferedImage.TYPE_INT_RGB);
        graphics2D = (Graphics2D)image.getGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        clear(); 
    }
    Graphics2D g2D = (Graphics2D) g;

    g2D.scale(zoom, zoom);
    g2D.drawImage(image, 0, 0, this);
    repaint();
}


public final void putPixelForLine(int x1, int y1, int x2, int y2, Color color) {
    if(graphics2D != null){
    graphics2D.setColor(color);
    graphics2D.drawLine(x1, y1, x2, y2);
    repaint();
    }
}

public void clear() {
    graphics2D.setPaint(Color.WHITE);
    graphics2D.fillRect(0, 0, getSize().width, getSize().height);
    repaint();
}

public void originalSize() {
    zoom = 1;
}

public void zoomIn() {
    zoom += percentage; 
    if(zoom > 1.66){
        zoom = 1.66;
    }   
        if(image != null){
            this.setPreferredSize(new Dimension((int)zoom*image.getWidth(),(int)zoom*image.getHeight()));
        }

    revalidate();     
    repaint();
}

public void zoomOut() {
    zoom -= percentage;
    if(zoom < 0.2){
        zoom = 0.2;
    }
        if(image != null){
            this.setPreferredSize(new Dimension((int)zoom*image.getWidth(),(int)zoom*image.getHeight()));
        }
    revalidate();     
    repaint();
}

}

1 个答案:

答案 0 :(得分:1)

我希望您遵循以下程序:

你有一个这样的循环

initiate the image
draw everything you want on the image: call pixelForLine() etc
while(true) {
  zoomIn();
  repaint();
  ... wait a bit
}

用于放大测试 - 相当于缩小。

您应该按如下方式更改方法:

a)在paint()或paintComponent中调用repaint()是一个明显的缺陷 - 删除那里的重绘。

b)如果你想看到缩放/缩小,改变jpanel的大小是没有意义的;如果你改变包含面板的大小,图像没有任何反应 - 两者都放大,所以没有任何变化。 (你在这里有相互矛盾的要求:似乎你把jpanel附加到某个地方,你想继续改变jpanel的大小 - 这不是很好的做法,但我把它留给你。) - 所以删除setPreferredSize ...的东西。如果你想在某处改变大小,请使用setSize();重绘(); (如有必要,可以验证())

public void zoomIn() {
    zoom += percentage; 
    if(zoom > 1.66){
        zoom = 1.66;
    }   
}

c)从pixelForLine()中删除repaint() - 在图像上绘制线条并重新绘制图像

d)(int)zoom image.getWidth()应为(int)(zoom image.getWidth())

相关问题