Java Draw Image drawScaledImage(Image image, Component canvas, Graphics g)

Here you can find the source of drawScaledImage(Image image, Component canvas, Graphics g)

Description

draw Scaled Image

License

LGPL

Declaration

public static void drawScaledImage(Image image, Component canvas, Graphics g) 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.awt.Component;
import java.awt.Graphics;

import java.awt.Image;

public class Main {
    public static void drawScaledImage(Image image, Component canvas, Graphics g) {
        int imgWidth = image.getWidth(null);
        int imgHeight = image.getHeight(null);

        double imgAspect = (double) imgHeight / imgWidth;

        int canvasWidth = canvas.getWidth();
        int canvasHeight = canvas.getHeight();

        double canvasAspect = (double) canvasHeight / canvasWidth;

        int x1 = 0; // top left X position
        int y1 = 0; // top left Y position
        int x2 = 0; // bottom right X position
        int y2 = 0; // bottom right Y position

        if (imgWidth < canvasWidth && imgHeight < canvasHeight) {
            // the image is smaller than the canvas
            x1 = (canvasWidth - imgWidth) / 2;
            y1 = (canvasHeight - imgHeight) / 2;
            x2 = imgWidth + x1;/*from ww  w .j a  v a 2 s . c o  m*/
            y2 = imgHeight + y1;

        } else {
            if (canvasAspect > imgAspect) {
                y1 = canvasHeight;
                // keep image aspect ratio
                canvasHeight = (int) (canvasWidth * imgAspect);
                y1 = (y1 - canvasHeight) / 2;
            } else {
                x1 = canvasWidth;
                // keep image aspect ratio
                canvasWidth = (int) (canvasHeight / imgAspect);
                x1 = (x1 - canvasWidth) / 2;
            }
            x2 = canvasWidth + x1;
            y2 = canvasHeight + y1;
        }

        g.drawImage(image, x1, y1, x2, y2, 0, 0, imgWidth, imgHeight, null);
    }
}

Related

  1. drawNormalImage(Rectangle2D bounds, Graphics2D g2, Image image, ImageObserver observer, int imageWidth, int imageHeight)
  2. drawOnto(final BufferedImage pDestination, final Image pSource)
  3. drawPixel(BufferedImage img, int x, int y, int color)
  4. drawPixel(int x, int y, Color color, BufferedImage displayMap)
  5. drawScaledImage(Graphics graphics, BufferedImage image, int x, int y, int w, int h, int left, int right)
  6. drawSquare(BufferedImage image, int x, int y, int size, int pixel)
  7. drawStretchedImage(Rectangle2D bounds, Graphics2D g2, Image image, ImageObserver observer)
  8. drawTiledImage(Rectangle2D bounds, Graphics2D g2, Image image, ImageObserver observer, int imageWidth, int imageHeight, int tilePadding)
  9. drawTransparentImageInOval(Graphics2D gr, Image img, Rectangle r, boolean noShrink, double transparency)