1

我正在编写一个在画布上绘制文本的函数。该功能支持垂直和水平对齐,以及文本方向。我的问题是当文本定向时无法计算正确的对齐方式。这是标题:

procedure drawText(canvas: TCanvas; pos: TPoint; Text: string;
  FontName: TFontName; FontSize: integer; FontColor: TColor; Angle: integer;
  Halign: THorizontalAlignement; Valign: TVerticalAlignement);

Halign可以是左、右或中心,Valign可以是顶部、底部或中心。

一切都适用于简单的非定向文本:

h := TextWidth(Text);
case Halign of
    haLeft: // do nothing;
    ;
    haRight: x := x - h;
    haCenter: x := x - ( h div 2 );
  end;

  v := TextHeight(Text);
  case Valign of
    vaTop:  // do nothing;
      ;
    vaBottom: y := y - v;
    vaCenter: y := y - ( v div 2 );
  end;
  Font.Orientation := Angle;
  textOut(x, y, Text );

我已经做了很多尝试来确定什么去哪里,并且我已经设法根据其对齐参数定位垂直文本,但是水平文本放错了位置。

我知道它与方向、宽度和高度有关,但我无法正确地弄清楚如何处理它。

调用水平规则过程的示例:

    drawText( bmp.canvas, point( x, viewOption.padding - DocumentRuleTextMargin), 
inttoStr( x ), 'arial', 8, clBLack, 0, haCenter, vaBottom ); 

调用 Vertical 规则的过程(令人讨厌的那个): drawText( bmp.canvas, Point( x - CDocumentRuleTextMargin, y ), inttostr( y ), 'arial', 8, clBlack, 900, haCenter, vaBottom);

这是结果:

示例 1

我试图通过修改计算过程中 y 位置的符号来摆脱这种情况,如下所示:

 v := TextHeight(Text);
  case Valign of
    vaTop:  // do nothing;
      ;
    vaBottom: y := y + v;
    vaCenter: y := y + ( v div 2 );
  end;  

垂直规则的结果更好,而水平规则的结果最差:

示例 2

4

3 回答 3

2

好的 - 简单没有用。那么,您需要做的是找到文本的中心位置,并在旋转后从那里计算“左上角”。问题是我不知道字体指向哪一点——我猜是左上角。假设是这样,那么您的功能将变为:

// get centre
case Halign of
    haLeft: x1 := x + (h div 2);
    haRight: x1 := x - (h div 2);
    haCenter: x1 := x; // do nothing
  end;

  v := TextHeight(Text);
  case Valign of
    vaTop:  y1 := y + (v div 2);
    vaBottom: y1 := y - (v div 2);
    vaCenter: y1 := y; // do nothing
  end;
  Font.Orientation := Angle;
  // calculate new top left - depending on whether you are using firemonkey
  // or VCL you may need to convert to floats and/or use Cosint
  // x := x1 - (w/2)*CosD(Angle) - (h/2)*SinD(Angle);
  x := x1 - ((w * CosInt(Angle * 10)) - (h*SinInt(Angle*10)) div 2000);
  //y := y1 - (w/2)*SinD(Angle) + (h/2)*CosD(Angle);
  y := y1 - ((w * SinInt(Angle * 10)) - (h*CosInt(Angle*10)) div 2000);
  textOut(x, y, Text );

由于您在代码中使用 Div,我猜您正在使用 VCL。

我建议您查找 SinInt 以了解其中的乘法和除法。注释显示了您将在 Firemonkey 中使用的浮点版本。

我没有测试过这段代码——我只是想展示数学。您将需要对自己进行微调。

于 2016-03-09T13:22:57.573 回答
0

我认为您的情况下的垂直规则应该是

drawText( bmp.canvas, Point( x - CDocumentRuleTextMargin, y ), inttostr( y ), 'arial', 8, clBlack, 900, haCenter, vaCenter);

因为您正在尝试与复选标记对齐,并且它们需要居中。更改您的算法按预期移动了垂直位置,因此看起来您的原始算法是正确的 - 只是您的应用程序是错误的。

于 2016-03-09T10:53:26.633 回答
0

问题是旋转文本时宽度和高度不会改变。

使用 90° 旋转时,返回 textHeight 函数的是实际(可见)宽度。表示可见高度的 textWidth 也是如此。

在这种情况下,不可能使用与水平文本相同的公式将旋转 90° 的文本垂直和水平居中(即:将宽度的一半减去 x 位置会导致位移过大)。

由于我只管理垂直和水平文本,我将通过测试方向属性来使用解决方法。当 900 然后我切换 textHeight 和 textwidth 结果来计算文本的对齐位置。

于 2016-03-09T10:54:34.917 回答