how to fill a triangle in c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <graphics.h>
void drawTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
line(x1, y1, x2, y2);
line(x2, y2, x3, y3);
line(x3, y3, x1, y1);
int minX = fmin(x1, fmin(x2, x3));
int minY = fmin(y1, fmin(y2, y3));
int maxX = fmax(x1, fmax(x2, x3));
int maxY = fmax(y1, fmax(y2, y3));
for (int i = minX; i <= maxX; i++) {
for (int j = minY; j <= maxY; j++) {
int sign1 = (x2 - x1) (j - y1) - (y2 - y1) (i - x1);
int sign2 = (x3 - x2) (j - y2) - (y3 - y2) (i - x2);
int sign3 = (x1 - x3) (j - y3) - (y1 - y3) (i - x3);
if ((sign1 >= 0 && sign2 >= 0 && sign3 >= 0) || (sign1 <= 0 && sign2 <= 0 && sign3 <= 0)) {
putpixel(i, j, RED);
}
}
}
delay(5000);
closegraph();
}
int main() {
int x1, y1, x2, y2, x3, y3;
printf("Enter coordinates of first point (x1 y1): ");
scanf("%d %d", &x1, &y1);
printf("Enter coordinates of second point (x2 y2): ");
scanf("%d %d", &x2, &y2);
printf("Enter coordinates of third point (x3 y3): ");
scanf("%d %d", &x3, &y3);
drawTriangle(x1, y1, x2, y2, x3, y3);
return 0;
}
Explanation:
1. Include necessary libraries: Include the required C standard libraries (stdio.h
, stdlib.h
, math.h
, graphics.h
) for input/output operations, mathematical functions, and graphics handling.
2. drawTriangle
function: Defines a function to draw a triangle and fill it with a color.
- Initializes the graphics system.
- Draws the three sides of the triangle using line()
function.
- Determines the minimum and maximum x and y coordinates of the triangle to set the boundary for filling.
- Iterates through each pixel within the boundary of the triangle.
- Uses the sign of three determinants to check if the pixel is inside the triangle. If so, fills the pixel with a red color using putpixel()
function.
- Delays for 5 seconds and closes the graphics system using delay()
and closegraph()
functions, respectively.
3. main
function:
- Prompts the user to enter the coordinates of three points for the triangle.
- Calls the drawTriangle
function with the provided coordinates.
- Returns 0 to indicate successful execution.