用java代码用for循环画几个画布为黑色,像素为800*480的,不等腰的白色三角形,并且保存到自定义的文件夹里
时间: 2023-05-21 19:03:41 浏览: 111
以下是用Java代码用for循环画不等腰的白色三角形的示例:
```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class DrawTriangle {
public static void main(String[] args) {
int width = 800;
int height = 480;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, width, height);
g.setColor(Color.WHITE);
int x1 = 0;
int y1 = height - 1;
int x2 = width / 2;
int y2 = 0;
int x3 = width - 1;
int y3 = height - 1;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (isInsideTriangle(x, y, x1, y1, x2, y2, x3, y3)) {
image.setRGB(x, y, Color.WHITE.getRGB());
}
}
}
File output = new File("custom_folder/triangle.png");
try {
ImageIO.write(image, "png", output);
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean isInsideTriangle(int x, int y, int x1, int y1, int x2, int y2, int x3, int y3) {
int area = (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));
int s = (x1 * (y2 - y) + x2 * (y - y1) + x * (y1 - y2));
int t = (x * (y2 - y3) + x2 * (y3 - y) + x3 * (y - y2));
return s >= 0 && t >= 0 && s + t <= area;
}
}
```
这段代码将在自定义文件夹中生成一个名为"triangle.png"的图像文件,其中包含一个不等腰的白色三角形。
阅读全文