使用DrawString将单个字符居中 [英] Centering an individual character with DrawString

查看:261
本文介绍了使用DrawString将单个字符居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了所有建议的居中文本方法,但是在居中放置单个字符时似乎无法获得想要的结果.

I have tried all of the suggested ways to center text, but I can't seem to get the results I want while centering an individual character.

我有一个矩形.在那个矩形中,我用DrawEllipse画了一个圆.现在,我想使用相同的矩形和DrawString在圆内绘制单个字符,以使其完全居中.

I have a rectangle. In that rectangle I'm drawing a circle with DrawEllipse. Now I want to draw a single character inside the circle using the same rectangle and DrawString, to have it perfectly centered.

这是我的基本代码:

StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;

using (Graphics g = Graphics.FromImage(xImage))
{
    g.SmoothingMode = SmoothingMode.AntiAlias;
    g.TextRenderingHint = TextRenderingHint.AntiAlias;
    g.CompositingQuality = CompositingQuality.HighQuality;
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.PixelOffsetMode = PixelOffsetMode.HighQuality;

    g.FillEllipse(fillBrush, imageRect.X, imageRect.Y, imageRect.Width - 1, imageRect.Height - 1);

    g.DrawString(Text, font, Brushes.White, imageRect, stringFormat);
}

文本在水平方向居中...但是在垂直方向上居中对齐不正确.使用类似大写字母"I"的对称字符,我发现字符的顶部总是比字符的底部更接近矩形的边缘.距离可能至少增加50%.

The text is centered horizontally... but it's not properly centered veritcally. Using a symmetrical character like an uppercase "I", I find that the top of the character is always much nearer to the edge of the rectangle than the bottom of the character. The distance is probably at least a 50% increase.

我假设它为像小写字母"j"这样的字符悬挂了足够的空间.但是,由于我试图创建一个带有单个字母的图形图标,因此我想更精确地居中.

I assume that it is measuring enough space for characters like a lowercase "j" which hangs lower. However, since I am trying to create a graphical icon with a single letter, I want more precise centering.

推荐答案

使用GraphicsPath完成尺寸计算.

public static void DrawCenteredText(Graphics canvas, Font font, float size, Rectangle bounds, string text)
{
    var path = new GraphicsPath();
    path.AddString(text, font.FontFamily, (int)font.Style, size, new Point(0, 0), StringFormat.GenericTypographic);

    // Determine physical size of the character when rendered
    var area = Rectangle.Round(path.GetBounds());

    // Slide it to be centered in the specified bounds
    var offset = new Point(bounds.Left + (bounds.Width / 2 - area.Width / 2) - area.Left, bounds.Top + (bounds.Height / 2 - area.Height / 2) - area.Top);
    var translate = new Matrix();
    translate.Translate(offset.X, offset.Y);
    path.Transform(translate);

    // Now render it however desired
    canvas.SmoothingMode = SmoothingMode.AntiAlias;
    canvas.FillPath(SystemBrushes.ControlText, path);
}

这篇关于使用DrawString将单个字符居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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