draw Stretched Image - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Effect

Description

draw Stretched Image

Demo Code

/**/*  ww w.j a va2 s  . c om*/
 * Copyright 1998-2008, CHISEL Group, University of Victoria, Victoria, BC, Canada.
 * All rights reserved.
 */
//package com.java2s;

import java.awt.Graphics2D;
import java.awt.Image;

import java.awt.geom.Rectangle2D;

import java.awt.image.ImageObserver;

public class Main {
    public static void drawStretchedImage(Rectangle2D bounds,
            Graphics2D g2, Image image, ImageObserver observer) {
        drawStretchedImage(bounds, g2, image, observer, false);
    }

    public static void drawStretchedImage(Rectangle2D bounds,
            Graphics2D g2, Image image, ImageObserver observer,
            boolean keepAspect) {
        int x = (int) bounds.getX();
        int y = (int) bounds.getY();
        int w = (int) bounds.getWidth();
        int h = (int) bounds.getHeight();
        if (keepAspect) {
            int imageWidth = image.getWidth(observer);
            int imageHeight = image.getHeight(observer);
            if ((imageWidth > 0) && (imageHeight > 0)) {
                double scaleWidth = bounds.getWidth() / imageWidth;
                double scaleHeight = bounds.getHeight() / imageHeight;
                if (scaleWidth < scaleHeight) {
                    h = (int) (scaleWidth * imageHeight);
                    // center vertically
                    y = y
                            + (int) Math.max(0, Math.round((bounds
                                    .getHeight() - h) / 2));
                } else {
                    w = (int) (scaleHeight * imageWidth);
                    // center horizontally
                    x = x
                            + (int) Math
                                    .max(0,
                                            Math.round((bounds.getWidth() - w) / 2));
                }
            }
        }
        // scales the image
        g2.drawImage(image, x, y, w, h, observer);
    }
}

Related Tutorials