繁体   English   中英

使用DrawText和GDI +创建透明的字形

[英]Create glyph transparent using DrawText with GDI+

我正在尝试创建一个函数来创建TBitmap。 此位图将是带有透明背景的字形,并且它只是Wingdings字体的一个字符。

之后,我将使用此标志符号将其分配给TBitBtn(按钮)。

这是我当前的代码:

function CreateTransparent(aChar: Char; aFontSize, aWidth, aHeight: Integer; aColor: TColor): TBitmap;

  function _GPColor(Col: TColor): TGPColor;
  begin
    Result := ColorRefToARGB(ColorToRGB(Col));
  end;

var
  f: TGPFont;
  r, rTx: TGPRectF;
  b: TGPSolidBrush;
  c: TGPGraphics;
  tx: TGPStringFormat;
  bt: TGPBitmap;
  h: HBITMAP;
  bk, fg: Cardinal;
  s: string;
  attr: TGPImageAttributes;
begin
  s := aChar;
  fg := _GPColor(aColor);

  bt := TGPBitmap.Create(abs(aWidth), aHeight, PixelFormat32bppARGB);
  try
    c := TGPGraphics.Create(bt);

    f := TGPFont.Create('Wingdings', aFontSize, FontStyleRegular, UnitPixel);
    b := TGPSolidBrush.Create( MakeColor(0, 0, 0, 0) );
    tx := TGPStringFormat.Create;
    try
      // configura o device
      tx.SetLineAlignment(StringAlignmentCenter);

      r.X := 0;
      r.Y := 0;
      r.Width := 2000;
      r.Height := aHeight;

      c.MeasureString(WideString(s), -1, f, r, rTx);
      if (aWidth < 0) and (rTx.Width > Abs(aWidth)) then
      begin
        c.Free;
        bt.Free;

        aWidth := Ceil(rTx.Width);

        bt := TGPBitmap.Create(aWidth, aHeight, PixelFormat32bppARGB);
        c := TGPGraphics.Create(bt);
      end;

      c.SetTextRenderingHint(TextRenderingHintAntiAlias);

      // inicializa as variáveis
      r.X := 0;
      r.Y := 0;
      r.Width := bt.GetWidth;
      r.Height := bt.GetHeight;

      // escreve o texto
      b.SetColor(fg);

      c.DrawString(WideString(s), -1, f, r, tx, b);
    finally
      f.Free;
      b.Free;
      tx.Free;
      c.Free;
    end;

    Result := TBitmap.Create;
    if bt.GetHBITMAP(0, h)= ok then
      TBitmap(Result).Handle := h;
  finally
    bt.Free;
  end;
end;

用法:

myGlyph := CreateTransparent('N', 14, 16, 16, clGray);

问题:

生成的位图不透明,背景变为黑色!

有人可以告诉我我需要做什么来“填充”透明背景吗?

据我了解,您希望位图的背景透明吗? 如果是这样,你需要使用alpha通道的位图..默认情况下,背景色为黑色,所以你只需要设置的属性AlphaFormat你的位图的afDefined

...
Result := TBitmap.Create;
Result.AlphaFormat := afDefined;
if bt.GetHBITMAP(0, h) = ok then
  TBitmap(Result).Handle := h;
...

这是结果:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM