0

是否可以在鼠标周围打印部分屏幕?我尝试:

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

但它会打印所有屏幕,我可以看到我可以设置矩形的大小,但我不知道如何将矩形居中以使其围绕鼠标。

4

3 回答 3

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));
}
于 2013-06-20T08:23:25.850 回答
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);

如果鼠标太靠近屏幕边缘,您可能会遇到奇怪的结果,但如果没有更多信息,这种特殊行为由您来定义您希望它如何。

于 2013-06-20T08:21:10.793 回答
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);
于 2013-06-20T08:22:38.660 回答