views:

3075

answers:

2

I have a multiline text string (e.g. "Stuff\nMore Stuff\nYet More Stuff"), and I want to paint it, along with a bitmap into a tooltip. Since I am painting the bitmap, I need to set OwnerDraw to true, which I am doing. I am also handling the Popup event, so I can size the tooltip to be large enough to hold the text and the bitmap.

I am calling e.DrawBackground and e.DrawBorder(), and then painting my bitmap on the left side of the tooltip area.

Is there a set of flags I can pass to e.DrawText() in order to left-align the text, but to offset it so that it doesn't get painted over my bitmap? Or do I need to custom draw all the text as well (which will probably involve splitting the string on newlines, etc)?

UPDATED: The final code looks like this:

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);
}
+1  A: 

I assume that if you define the bounding rectangle to draw in (calculating the image offset yourself) you could just:

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

Hi,

to calculate the Height of an owner drawn string s given a certain width w, we use the following code:

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;
}

Regards, tamberg

tamberg