How to take a custom shaped screenshot?

2019-06-09 17:50发布

问题:

For creating screenshots in Java i have been using the java.awt.Robot class' createScreenCapture() method. But i was only able to create screenshots in the Rectangle shape. Now my question is is there any way to take a screenshot of custom shape either by using the Robot class or some other explicit code?

And by the way, for custom shape the screenshot has to be transparent and i am likely to store it in PNG format.

Any answer is appreciated.

回答1:

is there any way to take a screenshot of custom shape either by using the Robot class or some other explicit code?

I like Andrew Thompson's solution that shows how to create a shaped image from a rectangular image. See Cut Out Image in Shape of Text.

You can do this with any shape. For example you can create your own Polygon by doing something like:

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


回答2:

Graphics#setClip(Shape) works fine (as camickr has already suggested):

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