如何拍摄自定义形状的截图?

时间:2013-07-20 18:42:13

标签: java swing screenshot awtrobot

要在Java中创建屏幕截图,我一直在使用java.awt.Robot类'createScreenCapture()方法。但我只能创建Rectangle形状的屏幕截图。现在我的问题是有没有办法通过使用Robot类或其他一些显式代码来截取自定义形状的截图?

顺便说一句,对于自定义形状,屏幕截图必须是透明的,我可能会将其存储为 PNG 格式。

感谢任何回答。

2 个答案:

答案 0 :(得分:3)

  

有没有办法通过使用Robot类或其他一些显式代码来获取自定义形状的屏幕截图?

我喜欢Andrew Thompson的解决方案,该解决方案展示了如何从矩形图像创建形状图像。见Cut Out Image in Shape of Text

你可以用任何形状做到这一点。例如,您可以通过以下操作创建自己的Polygon:

Polygon polygon = new Polygon();
polygon.addPoint(250, 50);
polygon.addPoint(350, 50);
polygon.addPoint(450, 150);
polygon.addPoint(350, 150);
g.setClip(polygon);
g.drawImage(originalImage, 0, 0, null);

答案 1 :(得分:2)

Graphics#setClip(Shape)工作正常(正如camickr已经建议的那样):

enter image description here

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ScreenShotClipTest {
  private JComponent makeUI() {
    JPanel p = new JPanel(new BorderLayout());
    p.add(new JScrollPane(new JTree()));
    p.add(new JButton(new AbstractAction("screenshot") {
      @Override public void actionPerformed(ActionEvent e) {
        JButton b = (JButton)e.getSource();
        Window f = SwingUtilities.getWindowAncestor(b);
        try {
          BufferedImage ss = new Robot().createScreenCapture(f.getBounds());
          int w = ss.getWidth(null), h = ss.getHeight(null);
          BufferedImage bi = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
          Graphics g = bi.createGraphics();
          g.setClip(new RoundRectangle2D.Float(0,0,w,h,64,64));
          g.drawImage(ss, 0, 0, null);
          g.dispose();
          ImageIO.write(bi, "png", new File("screenshot.png"));
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
    }), BorderLayout.SOUTH);
    return p;
  }
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() {
        createAndShowGUI();
      }
    });
  }
  public static void createAndShowGUI() {
    final JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(new ScreenShotClipTest().makeUI());
    f.setSize(320, 240);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}