Categories
Java

Drawing aliased lines with Java

Java provides a very flexible API for drawing images. This API also support aliased drawing of lines, text, etc. To activate it, you have to set the RenderingHints of the Graphics-Object (line 3). After that all operations results in aliased objects. To draw half pixels, you can use g.scale or g.translate with double-values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        BufferedImage image = new BufferedImage(200,200,BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(Color.white);
        g.fillRect(0, 0, 199, 199);
        g.setColor(Color.black);
        double step = 2.5;
        g.scale(step, 1);
        for (int i = 0; i < (int)(200/step); i++) {
            if (i % 2 == 1) {
                g.fillRect(0, 0, 1, 199);
            }
            g.translate(1, 0);
        }
        ImageIO.write(image, "png", new File("test.png"));

Leave a Reply

Your email address will not be published.