C#/ .NETのOwnerDraw Tooltipのテキスト配置
-
06-07-2019 - |
質問
複数行のテキスト文字列(例:" 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);
}
解決
描画する境界矩形を定義する(画像オフセットを自分で計算する)場合、次のことができると思います:
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;
}
よろしく、 タンバーグ
所属していません StackOverflow