如何在Delphi中使用DirectWrite在列表框的画布上使用绘图文本?

时间:2015-11-20 22:59:04

标签: delphi canvas vcl delphi-xe8 directwrite

我正在寻找一个简单的例子来使用TDirect2DCanvas为所有者绘制列表框的每个项目。谷歌搜索DirectWrite给出示例示例的结果,以在表单上呈现文本。作为一名学生,我的德尔菲技能无法正确掌握教程。一个简单的例子或在画布上绘制文本的参考对我来说是一个很好的开始。

这是代码(旧经典方法),我试图使用DirectWrite实现:

procedure TForm2.ListBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
var
  LB: TListBox;
begin
  LB := TListBox(Control);

  if odSelected in State then begin
    LB.Canvas.Brush.Color := clPurple;

  end;

  LB.Canvas.FillRect(Rect);
  LB.Canvas.TextOut(Rect.Left + 10, Rect.Top + 5, LB.Items[Index]);
end;

1 个答案:

答案 0 :(得分:0)

The code you posted would translate to something like the following:

var
  Direct2DCanvas: TDirect2DCanvas;
  LB: TListBox;
begin
  LB := TListBox(Control);

  Direct2DCanvas := TDirect2DCanvas.Create(LB.Canvas, LB.ClientRect);
  Direct2DCanvas.BeginDraw;
   try
    if odSelected in State then begin
      Direct2DCanvas.Brush.Color := clPurple;
    end;

    Direct2DCanvas.FillRect(Rect);
    Direct2DCanvas.TextOut(Rect.Left + 10, Rect.Top + 5, LB.Items[Index]);
  finally
    Direct2DCanvas.EndDraw;
    Direct2DCanvas.Free;
  end;
end;

However, keep in mind that the construction and destruction of a TDirect2DCanvas instance will slow things down a lot. In the end it might probably be slower than GDI as David pointed out.

This said it can be faster if done at a lower level and if a lot of drawing takes place or if you rely on anti-aliased drawing (which GDI can not offer).

To implement drawing at a lower level you must derive a custom TListBox component and implement handling resizing and drawing for an additional TDirect2DInstance (if this is available). This is explained in the (already provided) link by David.