0

我想将具有指定字体和透明背景的单个字符绘制到 SWT 图像,然后将其保存到文件中。我这样做:

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

角色已绘制,但背景为白色。我试图通过将 transparentPixel 设置为白色来解决它,这使背景透明但字符看起来很丑。我还尝试在图像上绘制任何内容之前将图像的 alphaData 设置为 0(完全透明),但 alphaData 在图像上绘制任何内容后不会更新,它始终保持透明。如何在图像上绘制具有透明背景的字符?

4

2 回答 2

0

你试过用 TYPE_INT_ARGB 绘制到 BufferedImage 吗?

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();
于 2012-07-25T18:43:53.887 回答
0

您必须使用中间 ImageData 来启用透明度

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;
于 2016-11-29T08:31:27.360 回答