用Java创建图像 [英] Creating images with a java
问题描述
您好)帮助解决问题: 我们需要创建一个绿色的正方形图像并将其显示.
Hello) Help solve the problem: We need to create a green square image and display it.
我可以画一个正方形,但是我需要使用java创建它. 请帮助我做到这一点) 那就是我试图做的:
I could draw a square, but I need to create it using java. Please help me to do this) That's what I tried to do:
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Game extends Canvas {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
@Override
public void paint(Graphics g) {
super.paint(g);
int w = 10;
int h = 10;
int type = BufferedImage.TYPE_INT_ARGB;
BufferedImage image = new BufferedImage(w, h, type);
int color = 257; // RGBA value, each component in a byte
for (int x = 1; x < w; x++) {
for (int y = 1; y < h; y++) {
image.setRGB(x, y, color);
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
frame.add(new Game());
frame.setVisible(true);
}
}
但是什么也没显示(
让我提醒我们的目标-以绿色方块的形式创建图片,帮助制作出来
Let me remind the goal - to create a picture in the form of green squares, help to make it)
推荐答案
最简单的方法是仅使用图形API ...
The simplest approach would be to simply use the graphics API...
@Override
public void paint(Graphics g) {
super.paint(g);
int w = 10;
int h = 10;
g.setColor(Color.GREEN);
g.fillRect(0, 0, width, height);
}
但是有些东西告诉我这不是您想要的,但这确实构成了实现结果所需的基础.
But something tells me this isn't what you want, but it does form the basics for what you need to achieve your result.
首先将图像作为实例字段...
Start by making image a instance field...
private BufferedImage image;
然后您需要创建图像...
Then you need to create the image...
int type = BufferedImage.TYPE_INT_ARGB;
image = new BufferedImage(w, h, type);
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.GREEN);
g2d.fillRect(0, 0, w, h);
g2d.dispoe();
然后在您的paint
方法中,您需要绘制图像...
Then in you paint
method, you need to draw the image...
g.drawImage(image, x, y, this);
看看 2D图形跟踪以了解更多详情
Take a look at the 2D Graphics trail for mor details
这篇关于用Java创建图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!