vendredi 27 février 2015

Robot.createScreenCapture() doesn't seem to match painting operations



I am trying to make a portion of my screen appear blurry. I grab pixel colors out of a BufferedImage where I saved a capture of the screen and draw the pixels again as bigger squares. But this only works when the paint method is called the first time, after that the affected pixels always stay the same even when the content of the screen updates. So it seems that even though the canvas is refreshed at the beginning of the paint method, the robot still sees the screen as it was previously...



@Override public void paintComponent(Graphics g) {
super.paintComponent(g);

screen = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));

int gap = 10; int width = 1920;
for (int r = 120; r <= 420; r += gap) {
for (int c = 500; c <= width - 500; c += gap) {
g.setColor(new Color(screen.getRGB(c, r)));
g.fillRect(c, r, gap, gap);
}
}
}


I tried clearing the painted area using clearRect() and sleeping the Thread at different positions, but it didn't work. Where do I need to put the createScreenCapture() so the painting actually updates?


This is the whole class:



import java.awt.AWTException;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Transparent extends JPanel implements Runnable {
private JFrame frame;
private Robot robot;
private BufferedImage screen;

public static void main(String[] args) {
new Transparent();
}

public Transparent() {
try {
robot = new Robot();
} catch (AWTException ex) {
ex.printStackTrace();
}

frame = new JFrame();
init();
frame.add(this);
frame.setUndecorated(true);
frame.setBackground(new Color(0, true));
frame.setAlwaysOnTop(true);
frame.setSize(1920, 1080);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);

new Thread(this).start();
}

public void init() {
setBackground(new Color(0, true));
setOpaque(false);
}

@Override public void paintComponent(Graphics g) {
super.paintComponent(g);

screen = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));

int gap = 5; int width = 1920;
for (int r = 120; r <= 420; r += gap) {
for (int c = 500; c <= width - 500; c += gap) {
g.setColor(new Color(screen.getRGB(c, r)));
g.fillRect(c, r, gap, gap);
}
}
}

@Override public void run() {
while (true) {
repaint();

try {
Thread.sleep(10);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}


}




Aucun commentaire:

Enregistrer un commentaire