Painting pixels images in Java

耗尽温柔 提交于 2019-12-03 07:25:55

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:

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

The key here is the Canvas class. It is the standard Component that allows arbitrary draw operations. In order to use it, you must subclass the Canvas class and override the paint(Graphics g) method, then loop through each pixel and draw your random color. The following code should work:

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);
    }
}

The generated image looks like this:

You'll probably want to create a BufferedImage of the size you want, and use img.setRGB(x, y, getRandomColor()) to create a bunch of random pixels. Then you could render the whole image wherever you want it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!