在框架上绘制自己的缓冲图像
我有我的框架大小的缓冲图像:
public BufferedImage img;
public static int WIDTH = 800;
public static int HEIGHT = 600;
img=new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
我如何绘制它,以便只能看到填充框架的黑色图像? 而不使用Canvas
我只想使用图形中的drawImage函数,而不使用paint或paintComponent函数
如果可能的话,我怎样才能为该图像分配一维数组[WIDTH * HEIGHT]?
简单:我想创建一个图像,将数组中的值转换为像素(0 =黑色,999999999 =浅蓝色等)并将其绘制到屏幕上。
编辑:
这是不能按预期工作的代码(它应该是一个带有黑色绘制图像的框架),但只是一个空白框架。为什么图像没有添加到框架?
import javax.swing.*;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
public class test extends Canvas{
public static JFrame frame;
public static int WIDTH = 800;
public static int HEIGHT = 600;
public test(){
}
public static void main(String[] a){
test t=new test();
frame = new JFrame("WINDOW");
frame.add(t);
frame.pack();
frame.setVisible(true);
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.start();
}
public void start(){
BufferedImage img = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
boolean running=true;
while(running){
BufferStrategy bs=this.getBufferStrategy();
if(bs==null){
createBufferStrategy(4);
return;
}
for (int i = 0; i < WIDTH * HEIGHT; i++)
pixels[i] = 0;
Graphics g= bs.getDrawGraphics();
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
g.dispose();
bs.show();
}
}}
据我了解你想达到什么(这不是很多),这可能会给你一些提示。 框架和图像的构造对我来说似乎仍然不整洁,但请仔细看看。
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.*;
public class TestImageDraw {
public static JFrame frame;
BufferedImage img;
public static int WIDTH = 800;
public static int HEIGHT = 600;
public TestImageDraw() {
}
public static void main(String[] a){
TestImageDraw t=new TestImageDraw();
frame = new JFrame("WINDOW");
frame.setVisible(true);
t.start();
frame.add(new JLabel(new ImageIcon(t.getImage())));
frame.pack();
// frame.setSize(WIDTH, HEIGHT);
// Better to DISPOSE than EXIT
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public Image getImage() {
return img;
}
public void start(){
img = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
boolean running=true;
while(running){
BufferStrategy bs=frame.getBufferStrategy();
if(bs==null){
frame.createBufferStrategy(4);
return;
}
for (int i = 0; i < WIDTH * HEIGHT; i++)
pixels[i] = 0;
Graphics g= bs.getDrawGraphics();
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
g.dispose();
bs.show();
}
}
}
一般提示
TestImageDraw
。