Direct2D (33) : 通过 ID2D1BitmapRenderTarget 绘制背景网格


ID2D1BitmapRenderTarget 是内存绘图的解决方案。它从 ID2D1RenderTarget 继承,只多出一个 GetBitmap() 方法。

{相关方法}
TDirect2DCanvas.RenderTarget.CreateCompatibleRenderTarget(); //建立 ID2D1BitmapRenderTarget
ID2D1BitmapRenderTarget.GetBitmap();                         //从 ID2D1BitmapRenderTarget 获取 ID2D1Bitmap


测试代码:

uses Direct2D, D2D1;

{通过 ID2D1BitmapRenderTarget 从内存建立 ID2D1BitmapBrush 的函数}
function GetBitmapBrush(RenderTarget: ID2D1RenderTarget): ID2D1BitmapBrush;
var
  iBitmapRenderTarget: ID2D1BitmapRenderTarget;
  rSizeF: TD2DSizeF;
  iSolidColorBrush: ID2D1SolidColorBrush;
  iBitmap: ID2D1Bitmap;
  rBitmapBrushProperties: TD2D1BitmapBrushProperties;
begin
  {根据指定大小建立 ID2D1BitmapRenderTarget}
  rSizeF := D2D1SizeF(10, 10);
  RenderTarget.CreateCompatibleRenderTarget(@rSizeF, nil, nil, D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS_NONE, iBitmapRenderTarget);

  {在 ID2D1BitmapRenderTarget 中绘图}
  RenderTarget.CreateSolidColorBrush(D2D1ColorF(clGreen), nil, iSolidColorBrush);
  iBitmapRenderTarget.BeginDraw;
  iBitmapRenderTarget.FillRectangle(D2D1RectF(0, 0, 10, 1), iSolidColorBrush);
  iBitmapRenderTarget.FillRectangle(D2D1RectF(0, 1, 1, 10), iSolidColorBrush);
  iBitmapRenderTarget.EndDraw();

  {从 ID2D1BitmapRenderTarget 输出 ID2D1Bitmap}
  iBitmapRenderTarget.GetBitmap(iBitmap);

  {根据刚刚获取的 ID2D1Bitmap 建立 ID2D1BitmapBrush}
  rBitmapBrushProperties.extendModeX := D2D1_EXTEND_MODE_WRAP;
  rBitmapBrushProperties.extendModeY := D2D1_EXTEND_MODE_WRAP;
  rBitmapBrushProperties.interpolationMode := D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR;
  RenderTarget.CreateBitmapBrush(iBitmap, @rBitmapBrushProperties, nil, Result);
end;

procedure TForm1.FormPaint(Sender: TObject);
var
  cvs: TDirect2DCanvas;
begin
  cvs := TDirect2DCanvas.Create(Canvas, ClientRect);
  cvs.BeginDraw;
  cvs.RenderTarget.Clear(D2D1ColorF(clBlack));
  cvs.Brush.Handle := GetBitmapBrush(cvs.RenderTarget);
  cvs.FillRectangle(ClientRect);
  cvs.EndDraw;
  cvs.Free;
end;

procedure TForm1.FormResize(Sender: TObject);
begin
  Repaint;
end;


效果图:



原文地址:https://www.cnblogs.com/del/p/2009542.html