Hello,
 
I am trying to implement a zoom on a BufferedImage. I have extended a JPanel and a simplified version of
its paintComponent( ) is shown below.
 
Each time paintComponent is called, the zoomFactor is increased by 0.1. So the first time it is called
zoomFactor is 1.0, then 1.1, then 1.2 etc.
 
After calling scale( ), I call translate( ) to move the image up and to the left in an effort to keep the center
of the image centered. However, what I find is: as the image grows larger, the center keeps moving up and
to the left until it 'floats' off the panel.
 
I guess I'm using the wrong value for translate( ) but can't figure out what it should be. I would think that it
should be half of the 'growth', i.e.  0.5f * ((width  * zoomFactor) - width); 
       
Am I making an obvious error?
 
Thank you,
 
Ted Hill
=======================
 
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
 
        Graphics2D g2 = (Graphics2D) g;
 
        final int   width      = bufImage.getWidth( );
        final int   height     = bufImage.getHeight( );
        final float zoomFactor = getZoomFactor( );
 
        // translate by half the 'growth'
        float translateX       = 0.5f * ((width  * zoomFactor) - width);
        float translateY       = 0.5f * ((height * zoomFactor) - height);
 
        // make image larger
        g2.scale(zoomFactor, zoomFactor);
 
        // keep image center centered
        g2.translate( - translateX, - translateY );
        
        g2.drawImage(bufImage, 0, 0, this);
    }
 
 

Reply via email to