2
votes

I have a polygon with the vertices (0,0), (100,0), (100,100), and (0,100). I debugged the program and those are the exact lines that java is drawing. Instead of drawing an exact square, some of the lines are a pixel too long:
http://gyazo.com/7418546c51c9a10fc690b18afcc96360.png
(The green circle is just me testing the centroid). When I move the square out of the corner, you can see that the top left corner is the only corner that is exactly correct. Why is this happening? Right before drawLine, I wrote the lines to the console after they were converted to integer coordinates, and they were correct. So I can't see what could possibly be wrong except for the drawLine functions. drawLine:

        g.drawLine((int) line.getStart().getX(), (int) line.getStart().getY(), 
            (int) line.getEnd().getX(), (int) line.getEnd().getY());

The line has a start vector and an end vector. The vectors contain an x and y.

Even when doing this:

    g.drawLine(0, 0, 100, 0);
    g.drawLine(100, 0, 100, 100);
    g.drawLine(100, 100, 0, 100);
    g.drawLine(0, 100, 0, 0);

It still produces the same result. This works though:

    g.drawLine(0, 0, 100, 0);
    g.drawLine(101, 0, 101, 100);
    g.drawLine(100, 101, 0, 101);
    g.drawLine(0, 100, 0, 0);
1
Please post your code. It's probably an off by one thing, but it's hard to say without seeing some code.jjm
Please provide the source code...Willem Van Onsem
Well we need to see how you called the method. Please provide a minimal working example...Willem Van Onsem
@CommuSoft Added codeMCMastery

1 Answers

3
votes

The example you provided is working:

    BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
    Graphics g = bi.getGraphics();
    g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
    g.setColor(Color.red);
    g.translate(50, 50);
    g.drawLine(0, 0, 100, 0);
    g.drawLine(100, 0, 100, 100);
    g.drawLine(100, 100, 0, 100);
    g.drawLine(0, 100, 0, 0);
    JOptionPane.showMessageDialog(null, new ImageIcon(bi));

There is a bug https://bugs.openjdk.java.net/browse/JDK-8049901 that describes one possible issue.