我正在尝试对齐一些大写文本,以使其看起来垂直居中于矩形:
var bmp = new Bitmap(size, size); // square bitmap
Font font = new Font("Tahoma", size * 3 / 8); // relative font size looks ok.
Graphics graphics = Graphics.FromImage(bmp);
Rectangle rectangle = new Rectangle(0, 0, size, size); // put font into the bitmap
StringFormat sf = new StringFormat(); // align vertically and horizontally!
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
graphics.FillRectangle(new SolidBrush(Color.Gray), rectangle);
graphics.DrawString("MB", font, Brushes.White, rectangle, sf);
现在,大写字母通常不使用下降,而仅使用上升(参见http://csharphelper.com/blog/2014/08/get-font-metrics-in-c/)。然而,对齐是考虑到下降而完成的,因此该字符串看起来像顶部一样,只有几个像素。
因此,我尝试使用链接中的类为DrawString引入垂直偏移量。但是,这不起作用,因为计算出的值似乎相距太远:
FontInfo fontInfo = new FontInfo(graphics, font);
int verticalOffset = (int)Math.Round(fontInfo.DescentPixels);
Rectangle rectangle2 = new Rectangle(0, verticalOffset, size, size);
graphics.DrawString("MB", font, Brushes.White, rectangle2, sf);
如何获得在图形中垂直居中的文本?