Here you can find the source of drawStretchedImage(Rectangle2D bounds, Graphics2D g2, Image image, ImageObserver observer)
public static void drawStretchedImage(Rectangle2D bounds, Graphics2D g2, Image image, ImageObserver observer)
//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); }//from w w w . ja v a2 s .co m 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); } }