Search code examples
javaeffectspixel

How would I make a static screen effect like a tv would have?


I want to make an effect that would look like the static on a old tv

I want it so it's moving and I'd rather not use multiple premade images to make the effect. How would I get this kind of effect with mono colors (black and white) lasting a period of about 3-5 seconds?


Solution

  • Try using the java.awt.Canvas class.

    Override the paint method in your canvas class, and than use this code to generate static:

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        for(int x = 0; x < getWidth(); x++){
            for(int y = 0; y < getHeight(); y++){
                int col = (int)(Math.round(Math.random()*100)%50);
                if(Math.random() > 0.5){
                    col = 255 - col;
                }
                g.setColor(new Color(col, col, col);
                g.fillRect(x, y, 1, 1);
            }
        }
    }
    

    What this is essentially doing is rendering a w*h grid is pixels, each with a value of 50 max for r, g, and b color values. This will make a grainy black-gray texture, and can be adapted to other grid matricies.

    EDIT:

    1. Changed from Canvas to JPanel, with paintComponent method.

    2. Made shade brighter or lighter based on random chance.