是否可以在鼠标周围打印部分屏幕? 我试着用:
Toolkit tool = Toolkit.getDefaultToolkit();
Dimension d = tool.getScreenSize();
Rectangle rect = new Rectangle(d);
Robot robot = new Robot();
File f = new File("screenshot.jpg");
BufferedImage img = robot.createScreenCapture(rect);
ImageIO.write(img,"jpeg",f);
但它打印所有屏幕,我可以看到我可以设置矩形的大小,但我不知道如何将矩形居中,以便它在鼠标周围。
答案 0 :(得分:3)
public static BufferedImage printScrAroundCursor(int width, int height)
{
Toolkit tool = Toolkit.getDefaultToolkit();
Robot robot = new Robot();
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
int x = (int) b.getX();
int y = (int) b.getY();
int topLeftX = Math.max(0, x - (width / 2));
int topLeftY = Math.max(0, y - (height / 2));
if (topLeftX + width > tool.getScreenSize().getWidth())
width = tool.getScreenSize().getWidth() - topLeftX;
if (topLeftX + width > tool.getScreenSize().getHeight())
width = tool.getScreenSize().getHeight() - topLeftY;
return robot.createScreenCapture(new Rectangle(topLeftX , topLeftY , width, height));
}
答案 1 :(得分:2)
您可以使用MouseInfo
获取鼠标的位置。从那里,它是简单的中点数学:
int width = ...;
int height = ...;
Point m = MouseInfo.getPointerInfo().getLocation();
Rectangle rect = new Rectangle(m.x - width / 2, m.y - height / 2, width, height);
Robot robot = new Robot();
File f = new File("screenshot.jpg");
BufferedImage img = robot.createScreenCapture(rect);
ImageIO.write(img, "jpeg" ,f);
如果鼠标距离屏幕边缘太近,您可能会遇到奇怪的结果,但是如果没有更多信息,这个特殊行为取决于您如何定义它。
答案 2 :(得分:0)
Point mousePos = MouseInfo.getPointerInfo().getLocation();
int width = 300;
int height = 300;
Point origin = new Point(mousePos.getX() - width / 2, mousePos.getY() - height / 2);
Rectangle rect = new Rectangle(origin.getX(), origin.getY(), width, height);
BufferedImage img = robot.createScreenCapture(rect);