Draw a polygon using the provided graphics object. Pass in pairs of integers as the points in the format: x1,y1,x2,y2,... - Java 2D Graphics

Java examples for 2D Graphics:Polygon

Description

Draw a polygon using the provided graphics object. Pass in pairs of integers as the points in the format: x1,y1,x2,y2,...

Demo Code


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;

public class Main{
    /**/*from w w w  .j  ava 2 s . c o  m*/
     * Draw a polygon using the provided graphics object.</br>
     * </br>
     * Pass in pairs of integers as the points in the format: </br>
     * x1,y1,x2,y2,...
     * 
     * @param g
     * @param p
     */
    public static void drawPolygon(Graphics g, int... p) {
        if (MathUtil.isOdd(p.length) || p.length == 0)
            throw new IllegalArgumentException();
        int n = p.length / 2;
        int[] x = new int[n];
        int[] y = new int[n];

        for (int i = 0; i < p.length; i++) {
            if (MathUtil.isEven(i)) {
                x[i / 2] = p[i];
            } else {
                y[i / 2] = p[i];
            }
        }
        g.drawPolygon(x, y, n);
    }
}

Related Tutorials