所有者的文本对齐在C#/.NET中绘制工具提示
我有一个多行文本字符串(例如“Stuff\nMore Stuff\nYet More Stuff”),我想将其与位图一起绘制到工具提示中。因为我正在绘制位图,所以我需要将OwnerDraw设置为true,我正在这样做。我还处理弹出事件,因此我可以调整工具提示的大小,使其足以容纳文本和位图 我正在调用e.trackground和e.DrawBorder(),然后在工具提示区域的左侧绘制位图 是否有一组标志可以传递给e.DrawText(),以使文本左对齐,但偏移它,使其不会在位图上绘制?或者我也需要自定义绘制所有文本(可能需要在换行符上拆分字符串等) 更新:最终代码如下所示:所有者的文本对齐在C#/.NET中绘制工具提示,c#,tooltip,ownerdrawn,drawstring,C#,Tooltip,Ownerdrawn,Drawstring,我有一个多行文本字符串(例如“Stuff\nMore Stuff\nYet More Stuff”),我想将其与位图一起绘制到工具提示中。因为我正在绘制位图,所以我需要将OwnerDraw设置为true,我正在这样做。我还处理弹出事件,因此我可以调整工具提示的大小,使其足以容纳文本和位图 我正在调用e.trackground和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);
}
我假设如果您定义要绘制的边界矩形(自己计算图像偏移),您可以:
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;
}
双测量高度(图形g、字符串s、字体f、整数w){
双结果=0;
int n=s.长度;
int i=0;
而(i=0){
i=i空间+1;
}否则{
我--;
}
//断言(w>行中最大的ch)
}
结果+=直线高度;
}
返回结果;
}
问候,,
坦伯格