Tom*_*983 7 java swing pixel graphics2d paintcomponent
哪种方法是使用java创建像素图像的最佳方法.比如,我想创建一个尺寸为200x200的像素图像,总共为40.000像素.如何从随机颜色创建像素并将其渲染到JFrame上的给定位置.
我试图创建一个只创建像素的自己的组件,但是如果我使用for循环创建这样一个像素250,000次并将每个实例添加到JPanels布局中,这似乎不是非常高效.
class Pixel extends JComponent {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(getRandomColor());
g.fillRect(0, 0, 1, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
您无需为此创建类.Java已经拥有出色的BufferedImage类,可以完全满足您的需求.这是一些伪代码:
int w = 10;
int h = 10;
int type = BufferedImage.TYPE_INT_ARGB;
BufferedImage image = new BufferedImage(w, h, type);
int color = 255; // RGBA value, each component in a byte
for(int x = 0; x < w; x++) {
for(int y = 0; y < h; y++) {
image.setRGB(x, y, color);
}
}
// Do something with image
Run Code Online (Sandbox Code Playgroud)
这里的关键是Canvas班级.它是Component允许任意绘制操作的标准.为了使用它,您必须对Canvas类进行子类化并覆盖该paint(Graphics g)方法,然后遍历每个像素并绘制随机颜色.以下代码应该有效:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
public class PixelCanvas extends Canvas {
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
private static final Random random = new Random();
@Override
public void paint(Graphics g) {
super.paint(g);
for(int x = 0; x < WIDTH; x++) {
for(int y = 0; y < HEIGHT; y++) {
g.setColor(randomColor());
g.drawLine(x, y, x, y);
}
}
}
private Color randomColor() {
return new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
frame.add(new PixelCanvas());
frame.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
生成的图像如下所示:
