C# / .NET 中 OwnerDraw 工具提示上的文本对齐
我有一个多行文本字符串(例如“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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设如果您定义要绘制的边界矩形(自己计算图像偏移),您可以:
I assume that if you define the bounding rectangle to draw in (calculating the image offset yourself) you could just:
要计算给定宽度 w 的所有者绘制的字符串 s 的高度,我们使用以下代码:
问候,
坦贝格
to calculate the Height of an owner drawn string s given a certain width w, we use the following code:
Regards,
tamberg