Direct2D (37) : 使用不同画刷绘制文本


uses Direct2D, D2D1;

{建立位图画刷的函数}
function GetBitmapBrush(Canvas: TDirect2DCanvas; filePath: string): ID2D1BitmapBrush;
var
  rBBP: TD2D1BitmapBrushProperties;
  bit: TBitmap;
begin
  bit := TBitmap.Create;
  bit.LoadFromFile(filePath);
  rBBP.extendModeX := D2D1_EXTEND_MODE_WRAP;
  rBBP.extendModeY := D2D1_EXTEND_MODE_WRAP;
  rBBP.interpolationMode := D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR;
  Canvas.RenderTarget.CreateBitmapBrush(Canvas.CreateBitmap(bit), @rBBP, nil, Result);
  bit.Free;
end;

{建立线性渐变画刷的函数}
function GetLinearGradientBrush(RenderTarget: ID2D1RenderTarget; Colors: array of TColor): ID2D1LinearGradientBrush;
var
  rLinear: TD2D1LinearGradientBrushProperties;
  rGradientStops: array of TD2D1GradientStop;
  iGradientStops: ID2D1GradientStopCollection;
  rSizeF: TD2DSizeF;
  count,i: Integer;
begin
  RenderTarget.GetSize(rSizeF);
  rLinear.startPoint := D2D1PointF(0, rSizeF.height/2);
  rLinear.endPoint := D2D1PointF(rSizeF.width, rSizeF.height/2);
  count := Length(Colors);
  SetLength(rGradientStops, count);
  for i := 0 to count - 1 do
  begin
    rGradientStops[i].position := i * (1 / (count-1));
    rGradientStops[i].color := D2D1ColorF(Colors[i]);
  end;
  RenderTarget.CreateGradientStopCollection(
    @rGradientStops[0], count, D2D1_GAMMA_2_2, D2D1_EXTEND_MODE_CLAMP, iGradientStops
  );
  RenderTarget.CreateLinearGradientBrush(rLinear, nil, iGradientStops, Result);
end;

procedure TForm1.FormPaint(Sender: TObject);
var
  cvs: TDirect2DCanvas;
  str: string;
  iTextFormat: IDWriteTextFormat;
  iBrush: ID2D1Brush;
begin
  str := 'Hello World using DirectWrite!';
  DWriteFactory.CreateTextFormat(
    'Gabriola',
    nil,
    DWRITE_FONT_WEIGHT_ULTRA_BLACK,
    DWRITE_FONT_STYLE_NORMAL,
    DWRITE_FONT_STRETCH_NORMAL,
    72.0,
    'en-us',
    iTextFormat
  );
  iTextFormat.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  iTextFormat.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);

  cvs := TDirect2DCanvas.Create(Canvas, ClientRect);
  cvs.RenderTarget.BeginDraw;
  cvs.RenderTarget.Clear(D2D1ColorF(clWhite));

  if Tag = 0 then
    iBrush := GetLinearGradientBrush(cvs.RenderTarget, [clRed, clYellow])
  else
    iBrush := GetBitmapBrush(cvs, 'C:\Temp\Test.bmp'); //!

  cvs.RenderTarget.DrawText(PWideChar(str), Length(str), iTextFormat, ClientRect, iBrush);
  cvs.RenderTarget.EndDraw();
  cvs.Free;
end;

{鼠标单击转换画刷}
procedure TForm1.FormClick(Sender: TObject);
begin
  Tag := not Tag;
  Repaint;
end;

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


效果图:



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