用Java代码用for循环画黑色画布,像素为150*150,白色菱形,并且保存到自定义的文件夹里
时间: 2023-05-22 20:03:09 浏览: 100
canvas:用于从 Java 代码绘制到画布的 API,以及 JavaFX 和 HTML5 的实现
可以尝试以下代码实现:
```
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Main {
public static void main(String[] args) {
int width = 150;
int height = 150;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, width, height);
int centerX = width / 2;
int centerY = height / 2;
int halfWidth = width / 2;
int halfHeight = height / 2;
int[] xPoints = {centerX, centerX + halfWidth, centerX, centerX - halfWidth};
int[] yPoints = {centerY - halfHeight, centerY, centerY + halfHeight, centerY};
g.setColor(Color.WHITE);
g.fillPolygon(xPoints, yPoints, 4);
File output = new File("custom_folder/diamond.png");
try {
ImageIO.write(image, "png", output);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
此代码先创建一个150x150像素的黑色画布,然后用四个点绘制出一个白色的菱形,并保存为PNG格式到自定义的文件夹(此处为"custom_folder")。
阅读全文