0

I want to draw single character with specified Font and transparent background to an SWT Image, later save it to file. I do it like this:

FontData fontData; // info about the font
char ch = 'a'; // character to draw

Display display = Display.getDefault();
TextLayout textLayout = new TextLayout(display);
textLayout.setAlignment(SWT.CENTER);
textLayout.setFont(font);
textLayout.setText("" + ch);
Rectangle r = textLayout.getBounds();
Image img = new Image(display, r.width, r.height);
GC gc = new GC(img);
textLayout.draw(gc, 0, 0);

The character is drawn but it gets white background. I tried to solve it by setting transparentPixel to white color, this makes background transparent but character looks ugly. I also tried to set alphaData of the Image with 0's (fully transparent) before drawing anything on it, but alphaData doesn't update after drawing anything on the Image, it stays transparent all the time. How to draw character with transparent background on the Image?

Mathias M
  • 483
  • 1
  • 5
  • 14

2 Answers2

0

Have u tried drawing to BufferedImage with TYPE_INT_ARGB?

Image fontImage= new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = fontImage.createGraphics();

//here u write ur code with g2d Graphics

g2d.drawImage(fontImage, 0, 0, null);
g2d.dispose();
java_xof
  • 439
  • 4
  • 16
  • Yes (as [here](http://stackoverflow.com/questions/4285464/java2d-graphics-anti-aliased/4287269#4287269)), but I tried to avoid mixing SWT and AWT, is there a method to do this using only SWT? – Mathias M Jul 26 '12 at 07:20
  • Hard to say, I'm not an expert; but if my memory is working fine swt was developed on the basis of awt so it could be very tricky to completely switch off awt from ur code. Anyway good luck with it! – java_xof Jul 26 '12 at 20:18
0

You have to use an intermediary ImageData to enable transparency

TextLayout textLayout = new TextLayout(font.getDevice());
textLayout.setText(s);
textLayout.setFont(font);
Rectangle bounds = textLayout.getBounds();
PaletteData palette = new PaletteData(0xFF, 0xFF00, 0xFF0000);
ImageData imageData = new ImageData(bounds.width, bounds.height, 32, palette);
imageData.transparentPixel = palette.getPixel(font.getDevice().getSystemColor(SWT.COLOR_TRANSPARENT).getRGB());
for (int column = 0; column < imageData.width; column++) {
    for (int line = 0; line < imageData.height; line++) {
        imageData.setPixel(column, line, imageData.transparentPixel);
    }
}
Image image = new Image(font.getDevice(), imageData);
GC gc = new GC(image);
textLayout.draw(gc, 0, 0);
return image;
Mickael
  • 3,506
  • 1
  • 21
  • 33