SWT中的字体到图像

时间:2012-07-25 15:26:51

标签: java swt

我想将具有指定Font和透明背景的单个字符绘制到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在图像上绘制任何内容后不会更新,它始终保持透明。 如何在图像上绘制透明背景的角色?

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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;
相关问题