Eva*_*man 6 c# height drawstring
我使用Graphics DrawString方法在图像上写文本,用RectangleF绑定我的文本.这是我的代码:
//Write header2
RectangleF header2Rect = new RectangleF();
header2Rect.Width = 600;
header2Rect.Location = new Point(30, 105);
graphicImage.DrawString(header2, new Font("Gotham Medium", 28, FontStyle.Bold),brush, header2Rect);
//Write Description
RectangleF descrRect = new RectangleF();
descrRect.Width = 600;
int measurement = ((int)graphicImage.MeasureString(header2, new Font("Gotham Medium", 28, FontStyle.Bold)).Height);
var yindex = int.Parse(105 + header2Rect.Height.ToString());
descrRect.Location = new Point(30, 105+measurement);
graphicImage.DrawString(description.ToLower(), new Font("Gotham", 24, FontStyle.Italic), SystemBrushes.WindowText, descrRect);
Run Code Online (Sandbox Code Playgroud)
这适用于某些情况(即,当header2只有1行长时),但我的measurement变量只测量字体的高度,而不是整个DrawString矩形.我不想设置静态header2Rect高度,因为高度会根据该文本而变化.
yindex不起作用,因为header2Rect.Height = 0.有没有办法看到我header2有多少行?
我只需要做MeasureString宽度并将其除以边界矩形宽度,然后乘以MeasureString高度?我假设有更好的方法.
谢谢
[编辑]看起来高度实际上是0,但文本只是溢出外面,但宽度仍然限制文本包装.我只是做了一些数学计算来找到高度,但我希望有更好的方法.
Lar*_*ech 10
你永远不会设置你的矩形高度:
private void panel1_Paint(object sender, PaintEventArgs e)
{
string header2 = "This is a much, much longer Header";
string description = "This is a description of the header.";
RectangleF header2Rect = new RectangleF();
using (Font useFont = new Font("Gotham Medium", 28, FontStyle.Bold))
{
header2Rect.Location = new Point(30, 105);
header2Rect.Size = new Size(600, ((int)e.Graphics.MeasureString(header2, useFont, 600, StringFormat.GenericTypographic).Height));
e.Graphics.DrawString(header2, useFont, Brushes.Black, header2Rect);
}
RectangleF descrRect = new RectangleF();
using (Font useFont = new Font("Gotham Medium", 28, FontStyle.Italic))
{
descrRect.Location = new Point(30, (int)header2Rect.Bottom);
descrRect.Size = new Size(600, ((int)e.Graphics.MeasureString(description, useFont, 600, StringFormat.GenericTypographic).Height));
e.Graphics.DrawString(description.ToLower(), useFont, SystemBrushes.WindowText, descrRect);
}
}
Run Code Online (Sandbox Code Playgroud)