Saturday, December 1, 2012

Translate and scale with AffineTransform

Translate and scale with AffineTransform
Translate and scale with AffineTransform

package javaswing;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

 * @web
public class JavaTestSwing {
    static JFrameWin jFrameWindow;
    public static class MyComponent extends JComponent{

        protected void paintComponent(Graphics g) {
            try {
                //prepare a original Image source
                Image image ="duke.png"));

                int w = image.getWidth(null);
                int h = image.getHeight(null);
                g.drawImage(image, 0, 0, w, h, null);

                //translate and scale with AffineTransform
                AffineTransform affineTransform = new AffineTransform();
                affineTransform.translate(0, h);
                Double sx = 2.0;
                Double sy = 2.0;
                affineTransform.scale(sx, sy);
                ((Graphics2D)g).drawImage(image, affineTransform, null);
            } catch (IOException ex) {
                Logger.getLogger(JavaTestSwing.class.getName()).log(Level.SEVERE, null, ex);

    public static class JFrameWin extends JFrame{
        public JFrameWin(){
            this.setSize(300, 300);
            MyComponent myComponent = new MyComponent();

    public static void main(String[] args){
        Runnable doSwingLater = new Runnable(){
            public void run() {
                jFrameWindow = new JFrameWin();


No comments:

Post a Comment