Thursday, June 2, 2022

Drawing an arch

Today I drew an arch using Java 2D. The difference with this example is firstly that we can use curves and secondly that this uses constructive area geometry.
 
public class Application {

    public static Shape arch(Rectangle bounds) {
        var p = new GeneralPath();

        var minX = bounds.getX();
        var minY = bounds.getY();
        var maxX = bounds.getMaxX();
        var maxY = bounds.getMaxY();

        p.moveTo(minX,maxY);
        p.lineTo(maxX, maxY);

        p.curveTo(maxX,maxY,maxX,minY,bounds.getCenterX(),minY);
        p.curveTo(minX,minY,minX,maxY,minX,maxY);
        p.closePath();

        return p;
    }

    public static Shape puncturedArch(Rectangle rect, int offset) {
        var arch1 = arch(rect);
        var newRectangle = new Rectangle(
                rect.x + offset,
                rect.y + offset,
                rect.width - 2*offset,
                rect.height-2*offset);
        var arch2 = arch(newRectangle);
        var area = new Area(arch1);
        area.subtract(new Area(arch2));
        return area;
    }

    public static BufferedImage makeImage() {
        var rval = new BufferedImage(300, 600, BufferedImage.TYPE_INT_ARGB);
        var g = rval.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        var cream = new Color(0xFFFDD0);
        var pineGreen = new Color(0x01796f);
        g.setPaint(new GradientPaint(0,0, new Color(0xB3190F) , 0,600, new Color(0x003DC4)));
        g.fill(puncturedArch(new Rectangle(0,0,300,600), 50  ));

        g.dispose();
        return rval;
    }

    public static void main(String[] args) throws IOException {
        var img = BasicImageProducer.padImage(makeImage(), new Insets(10,10,10,10));

        ImageIO.write(img, "png", new File(System.getProperty("user.home") + "/Media/arch.png"));

    }

}

Here is a picture of the arch. This time we used Image I/O so you don't have a picture of that whole JFrame. The fact that the punctured arch is a shape means that you can use contains on it, to create your own components or whatever you want.

No comments:

Post a Comment