gpt4 book ai didi

c# - 使用 Graphics.DrawString 时动态调整字体大小以适应空间

转载 作者:可可西里 更新时间:2023-11-01 03:06:13 26 4
gpt4 key购买 nike

有人可以动态调整字体大小以适应特定区域吗?例如,我有一个 800x110 的矩形,我想用支持我尝试显示的整个字符串的最大字体填充它。

Bitmap bitmap = new Bitmap(800, 110);

using (Graphics graphics = Graphics.FromImage(bitmap))
using (Font font1 = new Font("Arial", 120, FontStyle.Regular, GraphicsUnit.Pixel))
{
Rectangle rect1 = new Rectangle(0, 0, 800, 110);

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

graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
graphics.DrawString("Billy Reallylonglastnameinstein", font1, Brushes.Red, rect1, stringFormat);
}

bitmap.Save(Server.MapPath("~/Fonts/" + System.Guid.NewGuid() + ".png"));

显然,整个名称不会呈现在大字体提供的空间中。必须有一个简单的方法来做到这一点?

最佳答案

您应该对 Font.Size 进行缩放转换,以下函数是这样做的示例,但您可以对其进行改进以应用更好的结果。

这里是 FindFont 函数,它获取一个房间和一个具有首选大小的文本,并为您提供一种字体,您可以在其中设置整个文本适合房间!

// This function checks the room size and your text and appropriate font
// for your text to fit in room
// PreferedFont is the Font that you wish to apply
// Room is your space in which your text should be in.
// LongString is the string which it's bounds is more than room bounds.
private Font FindFont(
System.Drawing.Graphics g,
string longString,
Size Room,
Font PreferedFont
) {
// you should perform some scale functions!!!
SizeF RealSize = g.MeasureString(longString, PreferedFont);
float HeightScaleRatio = Room.Height / RealSize.Height;
float WidthScaleRatio = Room.Width / RealSize.Width;

float ScaleRatio = (HeightScaleRatio < WidthScaleRatio)
? ScaleRatio = HeightScaleRatio
: ScaleRatio = WidthScaleRatio;

float ScaleFontSize = PreferedFont.Size * ScaleRatio;

return new Font(PreferedFont.FontFamily, ScaleFontSize);
}

对于你的问题,你可以像下面的代码一样调用它:

Bitmap bitmap = new Bitmap(800, 110);

using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap))
using (Font font1 = new Font("Arial", 120, FontStyle.Regular, GraphicsUnit.Pixel))
{
Rectangle rect1 = new Rectangle(0, 0, 800, 110);

StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

Font goodFont = FindFont(graphics, "Billy Reallylonglastnameinstein", rect1.Size, font1);

graphics.DrawString(
"Billy Reallylonglastnameinstein",
goodFont,
Brushes.Red,
rect1,
stringFormat
);
}

关于c# - 使用 Graphics.DrawString 时动态调整字体大小以适应空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19674743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com