draw Tiled Image - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Effect

Description

draw Tiled Image

Demo Code

/**//  ww  w .  java2s.c  o  m
 * 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 drawTiledImage(Rectangle2D bounds, Graphics2D g2,
            Image image, ImageObserver observer, int imageWidth,
            int imageHeight, int tilePadding) {
        int x = (int) bounds.getX();
        int y = (int) bounds.getY();
        int w = imageWidth;
        int h = imageHeight;

        int cols = (int) Math.ceil(bounds.getWidth() / imageWidth);
        int rows = (int) Math.ceil(bounds.getHeight() / imageHeight);
        for (int row = 0; row < rows; row++) {
            if ((y + imageHeight) > bounds.getMaxY()) {
                h = (int) bounds.getMaxY() - y;
            }
            for (int col = 0; col < cols; col++) {
                w = imageWidth;
                if ((x + imageWidth) > bounds.getMaxX()) {
                    w = (int) bounds.getMaxX() - x;
                }
                // no scaling
                g2.drawImage(image, x, y, x + w, y + h, 0, 0, w, h,
                        observer);
                // move over a column
                x += w + tilePadding;
            }
            // go down a row
            y += h + tilePadding;
            x = (int) bounds.getX();
        }
    }
}

Related Tutorials