在Java中绘制像素图像
哪种方法是使用 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);
}
}
Which method is the best way to create a pixel image with java.
Say, I want to create a pixel image with the dimensions 200x200 which are 40.000 pixels in total. How can I create a pixel from a random color and render it at a given position on a JFrame.
I tried to create a own component which just creates pixel but it seems that this is not very performant if I create such a pixel a 250.000 times with a for-loop and add each instance to a JPanels layout.
class Pixel extends JComponent {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(getRandomColor());
g.fillRect(0, 0, 1, 1);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要为此创建一个类。 Java 已经有了优秀的 BufferedImage 类这正是你所需要的。这是一些伪代码:
You do not need to create a class for this. Java already has the excellent BufferedImage class that does exactly what you need. Here is some pseudo-code:
这里的关键是 Canvas 类。它是允许任意绘制操作的标准
Component
。为了使用它,您必须子类化Canvas
类并重写paint(Graphics g)
方法,然后循环遍历每个像素并绘制随机颜色。以下代码应该可以工作:生成的图像如下所示:
The key here is the
Canvas
class. It is the standardComponent
that allows arbitrary draw operations. In order to use it, you must subclass theCanvas
class and override thepaint(Graphics g)
method, then loop through each pixel and draw your random color. The following code should work:The generated image looks like this:
您可能想要创建一个所需大小的 BufferedImage ,并使用 img.setRGB(x, y, getRandomColor()) 来创建一堆随机像素。然后你可以在任何你想要的地方渲染整个图像。
You'll probably want to create a
BufferedImage
of the size you want, and useimg.setRGB(x, y, getRandomColor())
to create a bunch of random pixels. Then you could render the whole image wherever you want it.