用DrawString左右对齐文本 [英] Justify text with DrawString right -and- left

查看:462
本文介绍了用DrawString左右对齐文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有200个像素的空间,我想在其中画出两个字符串: -第一个字符串应保持对齐 -正确的第二个字符串应正确对齐 -但如果两者都不适合,则不要重叠(然后按照我的String.Trimming选项说的做任何事情)

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)

我需要测量每个并手动绘制吗,或者DrawString是否有某种方法可以支持我在不重新发明轮子的情况下想要做的事情?

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?

想象\ l和\ r是逃脱者,这样做,那么我可以说

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"

至少这是我想要发生的事情(我知道\ l和\ r不存在).有办法吗?

At least that's what I'd like to have happen (I know \l and \r do not exist). Is there a way?

推荐答案

我已经忽略了您的标志,而是(大致)向您展示了如何对齐文本.挑选文本,分割文本并将其绘制为两个单独的字符串非常容易!

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);
}

这篇关于用DrawString左右对齐文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆