2013-06-20 132 views
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); 

但它打印所有的屏幕,我可以看到,我可以设置矩形的大小,但我不知道怎样才能中心矩形,使其左右鼠标。

+0

如何鼠标周围区域多要打印? –

+0

我不知道也许300 x 300,它并不真正米。 – prowebphoneapp

回答

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

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

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