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