使用java graphic2D setclip(polygon) 函数剪切出来的图形不完整,不知道怎么回事,请高手指点
图片是一个 661x492的jpg文件,
完整代码如下:import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;public class OneStep1 extends JPanel {
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createUI();
} private void createUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scroll = new JScrollPane(new OneStep1());
f.setContentPane(scroll);
f.pack();
f.setVisible(true);
}
});
} public OneStep1() {
final BufferedImage image = loadImage("/images/elephant.jpg");
int[] xArray = { 300, 500, 400, 200, 100 };
int[] yArray = { 100, 200, 300, 300, 200 }; // make polygons
Polygon p = new Polygon(xArray, yArray, 5); // make image blocks
int type = BufferedImage.TYPE_INT_ARGB;
BufferedImage img = null;
Graphics2D g2 = null;
int pwidth = p.getBounds().width;
int pheight = p.getBounds().height;
System.out.println(pwidth + "-" + pheight);
img = new BufferedImage(pwidth, pheight, type);
g2 = img.createGraphics();
g2.setClip(p);
g2.drawImage(image, 0, 0, null);
g2.dispose(); // make labels to show image blocks
ImageIcon icon = new ImageIcon(img);
if (icon == null)
System.out.println("icon error.");
JLabel l = new JLabel(icon, JLabel.CENTER);
l.setBorder(BorderFactory.createTitledBorder("polygon"));
add(l); } private BufferedImage loadImage(String path) {
try {
return javax.imageio.ImageIO.read(getClass().getResource(path));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}