Justify text with DrawString right -and- left

天涯浪子 提交于 2019-12-23 04:36:24

问题


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:

  1. Call MeasureString on left string
  2. Call MeasureString on right string
  3. Draw left string, left-justified
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!