C#/.NET中OwnerDraw工具提示上的文本对齐方式

本文关键字:文本 对齐 方式 工具提示 NET OwnerDraw | 更新日期: 2023-09-27 17:48:49

我有一个多行文本字符串(例如"Stuff''nMore Stuff''nYet More Stuff"),我想把它和位图一起绘制到工具提示中。由于我正在绘制位图,我需要将OwnerDraw设置为true,我正在这样做。我还处理Popup事件,因此我可以将工具提示的大小调整为足够大,以容纳文本和位图。

我调用e.DrawBackground和e.DrawBorder(),然后在工具提示区域的左侧绘制位图。

有没有一组标志我可以传递给e.DrawText(),以便左对齐文本,但偏移它,这样它就不会被绘制在位图上?还是我需要自定义绘制所有文本(这可能涉及到在换行符上拆分字符串等)?

更新:最终代码如下:

private void _ItemTip_Draw(object sender, DrawToolTipEventArgs e)
{
  e.DrawBackground();
  e.DrawBorder();
  // Reserve a square of size e.Bounds.Height x e.Bounds.Height
  // for the image. Keep a margin around it so that it looks good.
  int margin = 2;
  Image i = _ItemTip.Tag as Image;  
  if (i != null)
  {
    int side = e.Bounds.Height - 2 * margin;  
    e.Graphics.DrawImage(i, new Rectangle(margin, margin, side, side));
  }
  // Construct bounding rectangle for text (don't want to paint it over the image).
  int textOffset = e.Bounds.Height + 2 * margin; 
  RectangleF rText = e.Bounds;
  rText.Offset(textOffset, 0);
  rText.Width -= textOffset;
  e.Graphics.DrawString(e.ToolTipText, e.Font, Brushes.Black, rText);
}

C#/.NET中OwnerDraw工具提示上的文本对齐方式

我假设如果你定义了要绘制的边界矩形(自己计算图像偏移量),你可以:

     RectangleF rect = new RectangleF(100,100,100,100);
     e.Graphics.DrawString(myString, myFont, myBrush, rect);

要计算给定宽度w的所有者绘制的字符串s的高度,我们使用以下代码:

double MeasureStringHeight (Graphics g, string s, Font f, int w) {
    double result = 0;
    int n = s.Length;
    int i = 0;
    while (i < n) {
        StringBuilder line = new StringBuilder();
        int iLineStart = i;
        int iSpace = -1;
        SizeF sLine = new SizeF(0, 0);
        while ((i < n) && (sLine.Width <= w)) {
            char ch = s[i];
            if ((ch == ' ') || (ch == '-')) {
                iSpace = i;
            }
            line.Append(ch);
            sLine = g.MeasureString(line.ToString(), f);
            i++;
        }
        if (sLine.Width > w) {
            if (iSpace >= 0) {
                i = iSpace + 1;
            } else {
                i--;
            }
            // Assert(w > largest ch in line)
        }
        result += sLine.Height;
    }
    return result;
}

谨致问候,tamberg