我需要在面板里面我能够绘制。我希望能够逐个像素地绘制。
ps:我不需要其他基元的行/圆。 pps:图形库并不重要,它可以是awt,swing,qt ......任何东西。我只想要一些通常由Bufferedimage表示的东西,或者像你设置单个像素颜色然后将其渲染到屏幕上的东西。
答案 0 :(得分:3)
一种方法的例子:
// Create the new image needed
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB );
for ( int rc = 0; rc < height; rc++ ) {
for ( int cc = 0; cc < width; cc++ ) {
// Set the pixel colour of the image n.b. x = cc, y = rc
img.setRGB(cc, rc, Color.BLACK.getRGB() );
}//for cols
}//for rows
然后从重写的paintComponent(Graphics g)
((Graphics2D)g).drawImage(img, <args>)
答案 1 :(得分:2)
由Bufferedimage代表..
我建议使用BufferedImage
,显示..
..或类似的东西,你设置单个像素的颜色,然后将其渲染到屏幕。
JLabel
中的.. - 见this answer。
当然,一旦我们有BufferedImage
的实例,我们就可以setRGB(..)
。
答案 2 :(得分:2)
如果你真的需要逐个像素地渲染,我已经为我为研究实验室编写的热点可视化软件片段做了很长时间。
你想要的是BufferedImage.setRGB(..) - 如果你逐个像素地绘制,我假设你已经实现了一个算法来渲染每个像素的RGB值(就像我们用热图所做的那样) )。这就是我们在当天使用的旧兼容IE的Applet中使用的内容。工作就像一个魅力,并且考虑到它的作用相对较快。
不幸的是,只要你在BufferedImage中直接操作RGB值,它就会被后备视频内存解除。
从Java 7开始,我听说底层的J2D实现会尝试在操作停止并重新渲染渲染后将图像重新缓存到视频内存中 - 例如,当你是渲染热图时它不会加速,但是一旦渲染,当您拖动窗口并使用应用程序时,支持图像数据可以重新加速。
答案 3 :(得分:0)
如果您想快速做某事,可以使用Graphics方法setColor和drawLine。例如:
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Set the colour of pixel (x=1, y=2) to black
g.setColor(Color.BLACK);
g.drawLine(1, 2, 1, 2);
}
我使用过这种技术并且速度不是很慢。我没有将它与使用BufferedImage对象进行比较。
答案 4 :(得分:0)
这里有点晚了,但是你可以像Java游戏程序员那样用Screen
类来做这件事:
public class Screen {
private int width, height;
public int[] pixels;
public Screen(int width, int height) {
this.width = width;
this.height = height;
pixels = new int[width * height];
}
public void render() {
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
pixels[x + y * width] = 0xFFFFFF; //make every pixel white
}
}
}
public void clear() {
for(int i = 0; i < pixels.length; i++) {
pixels[i] = 0; //make every pixel black
}
}
}
然后在你的主要班级:
private Screen screen;
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
screen.clear();
screen.render();
for(int i = 0; i < pixels.length; i++) {
pixels[i] = screen.pixels[i];
}
Graphics g = bs.getDrawGraphics();
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}
我觉得这应该有用。