TransWikia.com

Why is it that drawing a rectangle pixel by pixel with a for loop produces gaps?

Stack Overflow Asked by aurreco on February 28, 2021

I am currently working on a software rasterizer in Java using the swing and awt graphics libraries. Recently, I got a new computer and decided to transfer all my code to it. However, when I run the code, all the rasterized triangles have gaps in a grid-pattern.

I’ve narrowed the problem down to this: calling g.drawLine(x, y, x, y) (to put a pixel at the location (x, y)) in an embedded for loop where x and y are incremented is what seems to cause the gaps. Doing the same thing with g.fillRec(x, y, x, y) for example produces a solid color with no gaps.

Here is a sample code:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;

public class Test extends JPanel{
    
    JFrame frame;
    
    public Test() {
      frame = new JFrame();
      frame.setPreferredSize(new Dimension(400, 400));
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
      frame.pack();
      frame.add(this);
    }
    
    public static void main(String[] args) {
        new Test();
    }
    
    public void paintComponent(Graphics g){
        
      g.setColor(Color.red);
    
        for (int x = 0; x < 400; x++) {
            for (int y = 0; y < 400; y++) {
                g.drawLine(x, y, x, y);
            }
        }
    } 
}

And the result:

Picture of result

Is there any way I can fill a shape pixel by pixel in a for loop like this without seeing these gaps?

Thank you very much for any help.

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP