Draw the image with 9 grids scaling - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Scale

Description

Draw the image with 9 grids scaling

Demo Code

//   Licensed under the Apache License, Version 2.0 (the "License");
//package com.java2s;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;

public class Main {
    /**/*  w  w w .  j a v a2  s .c o  m*/
     * Draw the image with 9 grids scaling
     * 
     * @param g
     * @param img
     * @param dx1
     * @param dy1
     * @param dx2
     * @param dy2
     * @param insets
     * @param paintCenter
     */
    public static void drawImageWith9Grids(Graphics g, Image img, int dx1,
            int dy1, int dx2, int dy2, Insets insets, boolean paintCenter) {

        final int imgWidth = img.getWidth(null);
        final int imgHeight = img.getHeight(null);

        // top-left cornor
        g.drawImage(img, dx1, dy1, dx1 + insets.left, dy1 + insets.top, 0,
                0, insets.left, insets.top, null);
        // top-right cornor
        g.drawImage(img, dx2 - insets.right, dy1, dx2, dy1 + insets.top,
                imgWidth - insets.right, 0, imgWidth, insets.top, null);
        // bottom-left cornor
        g.drawImage(img, dx1, dy2 - insets.bottom, dx1 + insets.left, dy2,
                0, imgHeight - insets.bottom, insets.left, imgHeight, null);
        // bottom-right cornor
        g.drawImage(img, dx2 - insets.right, dy2 - insets.bottom, dx2, dy2,
                imgWidth - insets.right, imgHeight - insets.bottom,
                imgWidth, imgHeight, null);
        // top border
        g.drawImage(img, dx1 + insets.left, dy1, dx2 - insets.right, dy1
                + insets.top, insets.left, 0, imgWidth - insets.right,
                insets.top, null);
        // bottom border
        g.drawImage(img, dx1 + insets.left, dy2 - insets.bottom, dx2
                - insets.right, dy2, insets.left,
                imgHeight - insets.bottom, imgWidth - insets.right,
                imgHeight, null);
        // left border
        g.drawImage(img, dx1, dy1 + insets.top, dx1 + insets.left, dy2
                - insets.bottom, 0, insets.top, insets.left, imgHeight
                - insets.bottom, null);
        // right border
        g.drawImage(img, dx2 - insets.right, dy1 + insets.top, dx2, dy2
                - insets.bottom, imgWidth - insets.right, insets.top,
                imgWidth, imgHeight - insets.bottom, null);
        // center
        if (paintCenter) {
            g.drawImage(img, dx1 + insets.left, dy1 + insets.top, dx2
                    - insets.right, dy2 - insets.bottom, insets.left,
                    insets.top, imgWidth - insets.right, imgHeight
                            - insets.bottom, null);
        }
    }
}

Related Tutorials