Aligning text in OwnerDraw tooltip in C # /. NET
I have a multi-line text string (eg "Stuff \ nMore Stuff \ nYet More Stuff") and I want to draw it along with the bitmap in the tooltip. Since I am drawing a bitmap I need to set OwnerDraw to true, which is what I do. I also handle the Popup event, so I can tweak the tooltip just enough to hold the text and bitmap.
I call e.DrawBackground and e.DrawBorder () and then draw a bitmap on the left side of the tooltip area.
Is there a set of flags that I can pass to e.DrawText () to align the text to the left, but offset it so that it doesn't draw on top of my bitmap? Or do I need the custom to draw all the text (which would probably involve splitting the line into 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);
}
source to share
to calculate the height of the owner, drawn on line s with a specific 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
source to share