2
votes

I'm learning how to draw basic shapes using points in my graphics course, and I can't figure out how to draw a triangle. I thought it would be similar to drawing a rectangle, but a lot of variables (such as slope and different kinds of triangles) need to be taken into account.

Below is my working function of drawing a rectangle

drawRectangle(point 1, point 2){
    xStart = min(point 1.x, point 2.x)
    yStar = min(point 1.y, point 2.y)

    xEnd = max(point 1.x, point 2.x)
    yEnd = max(point 1.y, point 2.y)

    for(int i = yStart, i<= yEnd, i++){
        for(int j = xStart, j<= yEnd, j++){
            drawPoint(i, j);
        }
    }
}

drawRectangle is pretty straight forward, since I just have to loop over the starting point to the ending points of the vertices. However, a triangle has three points, what should I do? I thought about maybe dividing a triangle into two halves, so each half would have a flat "base", but I am not sure if that's a viable approach or not.

Edit: Maybe I was unclear, when I say draw a triangle, I meant a color-filled triangle

1
Are the 3 vertices available for the triangle? - Nabin
the 3 vertices are just random three points in a plane! - user3277633
So is it OK to compute slopes of the 3 sides of the triangle? - Nabin
Definitely. I do have a function drawLine that allows me to draw lines by given two points in the plane, not sure if that will help or not - user3277633
So why not just making equations and running through the equation to get each point in between two vertices? - Nabin

1 Answers

1
votes

You should use the Graphics interface for this. You just need to connect your three points with lines, like this:

void drawTriangle(Point one, Point two, Point three, Graphics g){
    g.drawLine(one.x, one.y, two.x, two.y);
    g.drawLine(one.x, one.y, three.x, three.y);
    g.drawLine(two.x, two.y, three.x, three.y);
}

This will draw a triangle, given three points and an instance of the Graphics object. This is a lot easier than using for loops.

EDIT:

Here is how to do this "from scratch", pixel by pixel using only the methods in your class (I am assuming that drawPoint draws 1 pixel), using the same "connect the dots" idea but with for loops:

drawTriangle(point 1, point 2, point 3) {
    for(int x = 1.x, x <= 2.x, x++){
        for(int y = 1.y, y <= 2.y, y++){
            drawPoint(x, y);
        }
    }
    for(int x = 1.x, x <= 3.x, x++){
        for(int y = 1.y, y <= 3.y, y++){
            drawPoint(x, y);
        }
    }
    for(int x = 2.x, x <= 3.x, x++){
        for(int y = 2.y, y <= 3.y, y++){
            drawPoint(x, y);
        }
    }
}

This connects all 3 points to each other.