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

时间:2008-11-07 07:42:32

标签: c# tooltip ownerdrawn drawstring

我有一个多行文本字符串(例如“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);
}

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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

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