首页 > 解决方案 > Cannot alignright text on canvas when orientation to vertical

问题描述

I am using the WinAPI DrawText to write to the canvas within a Rectangle. I have to write text horizontally and vertically. Using the uFormat constant to set how the text is aligned. I cannot get it to align vertical text to the top of the rectangle. see image

enter image description here

This is the code I am using to draw the text

  procedure SetOrientation(pIndex: Integer);
  var j: Integer;
  begin
    f := 0;
    j := fPinCount div 4;
    if pindex < j then begin
      fBuffer.Canvas.font.orientation := 0 ;
      f := DT_RIGHT
     end else
     if pIndex < 2 * j then begin
       fBuffer.Canvas.font.Orientation := 900 ;
       f := DT_TOP
      end else
      if pIndex < 3 * j then begin
        fBuffer.Canvas.font.orientation := 0;
        f := DT_LEFT
      end else begin
      fBuffer.Canvas.font.Orientation := 900;
        f := DT_LEFT;
    f := f or DT_SINGLELINE or DT_NOCLIP;
  end;

    SetOrientation(i);
    DrawText(FBuffer.Canvas.Handle, s, Length(s), PinDscRects[i], f);
    fBuffer.Canvas.Font.Orientation := 0;

I have tried all values of uFormat but none will justify the vertical text. Can you suggest an alternative method?

标签: delphiwinapi

解决方案


GDI是一个非常古老的图形 API,有时这很明显。有人可能会争辩说,这是其中一种情况。

但是,解决这个限制一点也不难。例如,你可以做

procedure TForm1.FormPaint(Sender: TObject);
const
  S = 'Nargles are cute!';
begin
  Canvas.Font.Orientation := 900;
  var R := ClientRect;
  OffsetRect(R, 0, Canvas.TextWidth(S));
  DrawText(Canvas.Handle, PChar(S), S.Length, R, DT_SINGLELINE or DT_NOCLIP);
end;

或(因为我认为这DT_NOCLIP部分有点难看)

procedure TForm1.FormPaint(Sender: TObject);
const
  S = 'Nargles are cute!';
begin
  Canvas.Font.Orientation := 900;
  TextOut(Canvas.Handle, 0, Canvas.TextWidth(S), PChar(S), S.Length);
end;

如您所见,我只是将传递给文本绘图函数的垂直空间坐标转换为文本的逻辑宽度(以像素为单位)。


推荐阅读