Search code examples
javadrawingawtpolygongraphics2d

Why is my building in Java not drawing properly?


I'm trying to draw a rectangle with a stylized edge on it, but unfortunately the edge only covers the left and top sides.

public Graphics2D Draw(Graphics2D b, long cameraX, long cameraY) {
    //let's do the drawing stuff, yay
    renderImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = renderImage.createGraphics();
    int[] xPs= new int[pointsarray.length];
    int[] yPs= new int[pointsarray.length];
    int i=0;
    for (Pair p:pointsarray){
        xPs[i]=p.pair[0];
        yPs[i]=p.pair[1];
        i++;
    }
    g.setColor(color);
    g.fillPolygon(xPs, yPs, xPs.length);
    g.setColor(color.darker());
    g.drawPolygon(xPs, yPs, xPs.length);
    b = super.Draw(b, cameraX, cameraY);
    return b;
}

Yes, it's a polygon. I have to keep this extendable.

EDIT: This is what pointsarray looks like for now.

    pointsarray = new Pair[4];

    pointsarray[0] = new Pair(0,0);
    pointsarray[1] = new Pair(0,height);
    pointsarray[2] = new Pair(width,height);
    pointsarray[3] = new Pair(width,0);

Render method: (this is overridden by the first method) (also I admit that the -renderImage.getWidth()/2 part was wrong)

public Graphics2D Draw(Graphics2D b ,long cameraX, long cameraY) {
    AffineTransform t = AffineTransform.getRotateInstance(r);
    AffineTransformOp op = new AffineTransformOp(t,AffineTransformOp.TYPE_BILINEAR);
    b.drawImage(renderImage, op, (int)(cameraX-x), (int)(cameraY-y));
    return b;
}

JFrame final render:

public void paintComponent(Graphics g) {
    Graphics2D r = (Graphics2D) g;
    Graphics2D b = (Graphics2D) r.create(); // i herd you liek buffers
    b.clearRect(0, 0, getWidth(), getHeight()); // clear the buffer
    // let's draw some... stuff
    long newCameraX = cameraX;
    long newCameraY = cameraY;
    // background
    b.setColor(Color.WHITE);
    b.fillRect(0, 0, getWidth(), getHeight());
    b.setColor(Color.BLACK);
    for (Entity entity : entities) {
        entity.Draw((Graphics2D) b, cameraX + (this.getSize().width / 2),
                cameraY + (this.getSize().height / 2));
    }

    // we're done drawing. let's put the stuff back in the first thing
    r = b;
    cameraX = newCameraX;
    cameraY = newCameraY;
}

Pair class:

public class Pair {
    public int[] pair = {0,0}; 

    public Pair(int num1, int num2) {
        pair[0] = num1;
        pair[1] = num2;
    }
    //you mad?
}

Solution

  • Basically you are drawing the bottom and right portions of your polygon outsize of the image. Java Graphics.fillPolygon: How to also render right and bottom edges?