英文:
Draw partially formatted strings in Windows Forms Graphics
问题
我一直在尝试绘制只在特定部分格式化的字符串,但无论我尝试的方法,包括使用Graphics.MeasureString,都导致了一些不对齐的问题,特别是在存在空格时。
我需要在字符串中绘制具有特殊格式的部分(例如不同颜色的单词),这些部分需要与其余未格式化的文本无缝匹配,并绘制到Graphics对象上。这将是程序化的,所以我不能手动测量值。字符串中格式化的部分可能会更改,因此我甚至不能偏离一个像素。
英文:
I have been struggling a lot with drawing strings that are only formatted on one specific part. Everything I have tried to do, including using Graphics.MeasureString, has resulted with something misaligned, especially when spaces are present.
I need to draw strings with special formatting in the middle (such as differently colored words) that seamlessly fit with the rest of the unformatted text onto a Graphics object. It will be procedural, so I can't manually measure out the values. The part of the string that is formatted may change so I can't even have one pixel off.
答案1
得分: 0
I had the similar issue of Graphics.MeasureString not being correct (inside TreeView.DrawNode), and fixed it by switching to TextRenderer. Someone else may be able to explain how to determine which one to use.
// Wherever you want to draw text
int x = e.Bounds.Left;
int y = e.Bounds.Top;
// Keep track of the width of the text drawn so far
int offsetX = 0;
// For each part of the string you want to draw,
// draw it and calculate its width
for (...)
{
TextRenderer.DrawText(
e.Graphics,
text,
font,
new Point(x + offsetX, y),
color,
// enable NoPrefix to disable processing of & as a prefix character
TextformatFlags.NoPrefix
);
offsetX += TextRenderer.MeasureText(
e.Graphics,
text,
font,
new Size(int.MaxValue, int.MaxValue),
// make sure NoPadding is enabled
TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding
).Width;
}
英文:
I had the similar issue of Graphics.MeasureString not being correct (inside TreeView.DrawNode), and fixed it by switching to TextRenderer. Someone else may be able to explain how to determine which one to use.
// Wherever you want to draw text
int x = e.Bounds.Left;
int y = e.Bounds.Top;
// Keep track of the width of the text drawn so far
int offsetX = 0;
// For each part of the string you want to draw,
// draw it and calculate its width
for (...)
{
TextRenderer.DrawText(
e.Graphics,
text,
font,
new Point(x + offsetX, y),
color,
// enable NoPrefix to disable processing of & as a prefix character
TextformatFlags.NoPrefix
);
offsetX += TextRenderer.MeasureText(
e.Graphics,
text,
font,
new Size(int.MaxValue, int.MaxValue),
// make sure NoPadding is enabled
TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding
).Width;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论