从JDK1.6好像是第10个updat版本开始,就可以使用com.sun.awt.AWTUtilities,去创建透明窗体和不规则窗体。例如要显示一张不规则图片,可以如下做:
JFrame jFrame = new JFrame();
jFrame.setUndecorated(true);
final ImageIcon imageIcon = ...;
final JPanel jLabel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
g.drawImage(imageIcon.getImage(), 0, 0, null);
}
};
AWTUtilities.setWindowOpaque(jFrame, false);
jFrame.getContentPane().add(jLabel);
这个窗体很好的显示了原图片,包括不规则性和透明性。
不过在SWT中,这个问题却不容易解决,我不知道有哪个现成的方法可以简单的实现。唯一可以用的就是Shell的setRegion(Region)方法。
网上有一段代码如下:
Region region = new Region();
final ImageData imageData = image.getImageData();
if (imageData.alphaData != null) {
Rectangle pixel = new Rectangle(0, 0, 1, 1);
for (int y = 0; y < imageData.height; y++) {
for (int x = 0; x < imageData.width; x++) {
if (imageData.getAlpha(x, y) == 255) {
pixel.x = imageData.x + x;
pixel.y = imageData.y + y;
region.add(pixel);
}
}
}
} else {
ImageData mask = imageData.getTransparencyMask();
Rectangle pixel = new Rectangle(0, 0, 1, 1);
for (int y = 0; y < mask.height; y++) {
for (int x = 0; x < mask.width; x++) {
if (mask.getPixel(x, y) != 0) {
pixel.x = imageData.x + x;
pixel.y = imageData.y + y;
region.add(pixel);
}
}
}
}
shell.setRegion(region);
通过按点计算Region,构造出shell的region出来,然后将图画出来:
if (e.type == SWT.Paint) {
e.gc.drawImage(image, imageData.x, imageData.y);
}
不过这并不是一个细致的过程,最大的一个问题就是图片原有的透明性丢失,如果原图中有些点是不完全不透明或说不完全透明,则最后显示出来的结果中不能体现这一点。