我有一个带有框架大小的缓冲图像:
public BufferedImage img;
public static int WIDTH = 800;
public static int HEIGHT = 600;
img=new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
我如何绘制它以便只能看到填充框架的黑色图像?不使用Canvas
我想在不使用paint或paintComponent函数的情况下仅使用图形中的drawImage函数
如果可能的话,我如何为该图像分配1D阵列[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();
}
}}
答案 0 :(得分:9)
据我所知,你想要达到的目标是什么(不是很多&#39;),这可能会给你一些提示。框架和图像的构造对我来说似乎仍然不整齐,但看看这个。
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
。