Smooth corners of a polygon. - Java java.lang

Java examples for java.lang:Math Geometry Shape

Description

Smooth corners of a polygon.

Demo Code


//package com.java2s;

import java.awt.Point;
import java.awt.Polygon;

import java.awt.geom.GeneralPath;

import java.awt.geom.Path2D;

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**/*from w w  w . java  2s .  c  om*/
     * Smooth corners of a polygon. Take polygon as input
     * 
     * @param polygon
     * @return Path of smoothed region
     */
    public static Path2D getRoundedGeneralPath(Polygon polygon) {
        List<int[]> l = new ArrayList<int[]>();
        for (int i = 0; i < polygon.npoints; i++) {
            l.add(new int[] { polygon.xpoints[i], polygon.ypoints[i] });
        }
        return getRoundedGeneralPath(l);
    }

    /**
     * Smooth corners of a polygon. Take an int array as input
     * 
     * @param l
     * @return
     */
    public static Path2D getRoundedGeneralPath(List<int[]> l) {
        List<Point> list = new ArrayList<Point>();
        for (int[] point : l) {
            list.add(new Point(point[0], point[1]));
        }
        return getRoundedGeneralPathFromPoints(list);
    }

    /**
     * Smooth corners of a polygon. Take a list of points as input
     * 
     * @param l
     * @return
     */
    public static Path2D getRoundedGeneralPathFromPoints(List<Point> l) {
        l.add(l.get(0));
        l.add(l.get(1));
        GeneralPath p = new GeneralPath();
        Point begin = calculatePoint(l.get(l.size() - 1), l.get(0));
        p.moveTo(begin.x, begin.y);
        for (int pointIndex = 1; pointIndex < l.size() - 1; pointIndex++) {

            Point p1 = l.get(pointIndex - 1);
            Point p2 = l.get(pointIndex);
            Point p3 = l.get(pointIndex + 1);
            Point m1 = calculatePoint(p1, p2);
            p.lineTo(m1.x, m1.y);
            Point m2 = calculatePoint(p3, p2);
            p.curveTo(p2.x, p2.y, p2.x, p2.y, m2.x, m2.y);
        }
        return p;
    }

    /**
     * 
     * @param p1
     * @param p2
     * @return
     */
    private static Point calculatePoint(Point p1, Point p2) {
        double arcSize = 0.4;

        double per = arcSize;
        double d_x = (p1.x - p2.x) * per;
        double d_y = (p1.y - p2.y) * per;
        int xx = (int) (p2.x + d_x);
        int yy = (int) (p2.y + d_y);
        return new Point(xx, yy);
    }
}

Related Tutorials