PNG image with transparency on SWT
I've got a Composite and would like to use a png file as background image. I can do that, the problem is when th开发者_如何学编程e image uses transparency it doesn't work and shows a white colour instead. Any thoughts on how to get this to work?
Thanks!
Does this article help?
Taking a look at SWT Images
It talks about drawing an image (albeit a GIF) to a Canvas
with transparency (Canvas
extends Composite
).
SOLVED! I've solved exactly this problem - displaying PNG files that contain transparent areas. I could not get it to work with Labels (in fact the article quoted states "Label does not support native transparency") so I put the image directly into a canvas instead. The other key to success is to use the Image constructor that includes a 3rd parameter, which is the transparency mask. An extra step I did is to call setRegion, which means that mouse events (such as mouse clicks) only fire when they occur over visible pixels.
ImageData id = new ImageData("basket.png");
Image image = new Image (display, id, id); //3rd parameter is transparency mask
Canvas c = new Canvas (shell, SWT.TRANSPARENT);
c.addPaintListener(
new PaintListener(){
public void paintControl(PaintEvent e)
{
e.gc.drawImage(image, 0, 0);
}
}
);
//the image has been created, with transparent regions. Now set the active region
//so that mouse click (enter, exit etc) events only fire when they occur over
//visible pixels. If you're not worried about this ignore the code that follows
Region region = new Region();
Rectangle pixel = new Rectangle(0, 0, 1, 1);
for (int y = 0; y < id.height; y++)
{
for (int x = 0; x < id.width; x++)
{
if (id.getAlpha(x,y) > 0)
{
pixel.x = id.x + x;
pixel.y = id.y + y;
region.add(pixel);
}
}
}
c.setRegion(region);
精彩评论