问题
Let's say I have 200 pixels of space and I want to draw two strings into it: - the first string should be left justified - right second string should be right justified - But not overlap if they do not both fit (then do whatever my String.Trimming options say)
Am I going to have to measure each and draw this manually, or does DrawString have some way to support what I'm trying to do without me reinventing the wheel?
Imagine that \l and \r were escapes that did this, then I could say
graphics.Drawstring("\lfirst\rsecond", ...);
and I'd wind up with something like
"first second"
At least that's what I'd like to have happen (I know \l and \r do not exist). Is there a way?
回答1:
I've ignored your flags and instead I'm showing you (roughly) how you can align text. It's easy enough to pick out your text, split it up and draw it as two separate strings!
string text2 = "Use TextFormatFlags and Rectangle objects to"
+ " align text in a rectangle.";
using (Font font2 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point))
{
Rectangle rect2 = new Rectangle(150, 10, 130, 140);
// Create a TextFormatFlags with word wrapping, horizontal center and
// vertical center specified.
TextFormatFlags flags = TextFormatFlags.HorizontalLeft |
TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;
// Draw the text and the surrounding rectangle.
TextRenderer.DrawText(e.Graphics, text2, font2, rect2, Color.Blue, flags);
e.Graphics.DrawRectangle(Pens.Black, rect2);
}
回答2:
In the long run here's what I wound up doing:
- Call MeasureString on left string
- Call MeasureString on right string
- Draw left string, left-justified
- If the sum of the width of the two strings is less than width of the available space, draw the right string right-justified.
Pretty straightforward, though I was hoping there was something in the framework that would have done the work for me.
来源:https://stackoverflow.com/questions/10889417/justify-text-with-drawstring-right-and-left