简体   繁体   English

如何在不修剪的情况下使用DrawString?

[英]How do I use DrawString without trimming?

I find the way the DrawString function cuts off entire characters or words to be counterintuitive. 我发现DrawString函数切断整个字符或单词的方式是违反直觉的。 Showing parts of the text clearly conveys that something is missing. 显示文本的一部分清楚地表明缺少某些东西。

Here are some examples: 这里有些例子:

StringTrimming.None: StringTrimming.None: 在此输入图像描述

StringTrimming.Character: StringTrimming.Character: 在此输入图像描述

What I want: 我想要的是: 在此输入图像描述 (GIMP mockup) (GIMP模型)

Is StringTrimming.None the same as StringTrimming.Character? StringTrimming.None和StringTrimming.Character一样吗? They seem to behave exactly alike in my case. 在我的案例中,他们似乎表现得完全相同。 Is there something I could have overlooked or is this a known "feature"? 有什么我可以忽略或这是一个已知的“功能”?

According to the docs StringTrimming.None "Specifies no trimming." 根据文档 StringTrimming.None“指定不修剪”。

This site with examples created with Java even show "None" to trim more characters than "Character". 使用Java创建的示例的此站点甚至显示“无”以修剪比“字符”更多的字符。

Are there other tricks to get this effect? 还有其他技巧可以达到这个效果吗?

Note: I do not want to display "…" or similar. 注意:我不想显示“......”或类似内容。 I find this to be a waste of space but that is probably a discussion for UX . 我发现这是浪费空间,但这可能是对UX的讨论。

It's possible that the text appears to be trimmed because it's actually wrapping invisibly onto the next line. 文本可能会被修剪,因为它实际上是无形地包裹到下一行。 In the call to Graphics.DrawString , disable wrapping by passing a StringFormat object whose FormatFlags property is set to NoWrap : 在对Graphics.DrawString的调用中,通过传递FormatFlags属性设置为NoWrapStringFormat对象来禁用包装:

StringFormat format =
    new StringFormat
    {
        FormatFlags = StringFormatFlags.NoWrap,
        Trimming = StringTrimming.None
    };
g.DrawString(s, font, brush, rect, format);

As a workaround, you can give the DrawString method a bigger RectangleF than you really want, and set the clipping region of your Graphics object to the actual RectangleF you want to draw the string in. 作为一种变通方法,您可以为DrawString方法提供比您真正想要的更大的RectangleF ,并将Graphics对象的剪切区域设置为您想要绘制字符串的实际RectangleF

RectangleF rect = new RectangleF(10, 10, 30, 15);
e.Graphics.DrawRectangle(Pens.Red, Rectangle.Truncate(rect));

RectangleF fakeRect = new RectangleF(rect.Location, new SizeF(short.MaxValue, short.MaxValue));

Region r = e.Graphics.Clip;
e.Graphics.SetClip(rect);            
e.Graphics.DrawString("1 Default", this.Font, SystemBrushes.ControlText, fakeRect);
e.Graphics.Clip = r;

Note that this code assumes you wish to anchor your text to the top left corner of the rectangle. 请注意,此代码假定您希望将文本锚定到矩形的左上角。 Otherwise you should generate the fake rectangle in a method that maintains the same anchor point as your intended layout rectangle. 否则,您应该在一个方法中生成假矩形,该方法保持与预期布局矩形相同的锚点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM