Is there a function equivalent to drawPixel in Java?

2

I wanted to know if there is a function in java that plots a pixel, something like drawPixel or setPixel that I see in some other programming languages, where you inform as parameters the X and Y coordinates and the pixel color to be plotted . I do not want drawLine style functions or something equivalent.

    
asked by anonymous 10.03.2015 / 03:10

1 answer

3

Yes, of course. You can use setRGB(x, y, cor) and getRGB(x, y) of the class BufferedImage .

You can get BufferedImage by using one of your builders , or load an external image. For example:

BufferedImage imagem = new BufferedImage(largura, altura, BufferedImage.TYPE_INT_ARGB);

This will create a blank image in memory. The third parameter is the image type, which in the case of TYPE_INT_ARGB "means that each pixel is represented by a int where the 8 most significant bits are the alpha , the next 8 bits are red, plus 8 bits of green, and the 8 less significant bits are blue.

Another way to get an image is to load it from an external resource (using the ImageIO ):

private static BufferedImage carregarImagem() throws IOException {
    try {
        return ImageIO.read(new URL("http://example.com/imagem.jpg"));
    } catch (MalformedURLException e) {
        throw new AssertionError(e);
    }
}

To make other more complex operations (draw circles, polygons, lines, etc.), you can get an object Graphics2D :

BufferedImage imagem = ...;
Graphics2D g2 = imagem.createGraphics();

And to draw another image within your Graphics2D (or your superclass Graphics ), you can use the drawImage ":

g.drawImage(imagem, posicaoX, posicaoY, null);

If you want to draw these images on the screen (either to plot graphics, or to make games with animations), you can begin by overwriting the paintComponent(Graphics) " of any JComponent . For example:

JPanel jp = new JPanel() {
    @Override
    public void paintComponent(Graphics g) {
        // Coloque aqui sua lógica de desenho.
    }
};

Note that the parameter type is Graphics . However, AWT will always provide an instance of Graphics2D , and in this case it is always safe to cast. So, to draw a component (including to make animations and games), you can create a BufferedImage , draw in it the pixels you want using the methods getRGB(x, y) , setRGB(x, y, cor) and createGraphics() , and in the end draw the image resulting in the component:

JPanel jp = new JPanel() {
    @Override
    public void paintComponent(Graphics g) {
        g.drawImage(imagem, posicaoX, posicaoY, null);
    }
};

One suggestion given by @array in a comment is to use the fillRect(x, y, largura, altura) of class Graphics " (in combination with the setColor(Color) ). So if you can plot the pixel directly in Graphics if you do not have an easily accessible BufferedImage matching:

Graphics g = ...;
g.setColor(...);
fillRect(posicaoX, posicaoY, 1, 1);
    
10.03.2015 / 03:47