C#使用最大字体大小将字符串添加到图像

时间:2012-03-17 05:32:03

标签: c# asp.net image-processing

我想在图像中添加2个字符串,如下所示:

This is Text
------------
------------
------------
--Other-----

如果不使用字符串偏离图像的一侧,如何使用最大的字体大小?

示例:如果文字太大,那么它就会脱离图片::

This is Text That is too big
------------
------------
------------
--Other-----

2 个答案:

答案 0 :(得分:3)

我在之前的项目中编写了这个脚本,通过计算每个字体大小的尺寸来将一些文本放入图像中。当字体大小大于图像的宽度时,它会将字体大小降低0.1em,然后再次尝试直到文本适合图像。这是代码:

public static string drawTextOnMarker(string markerfile, string text, string newfilename,Color textColor)
    {
        //Uri uri = new Uri(markerfile, UriKind.Relative);
        //markerfile = uri.AbsolutePath;
        //uri = new Uri(newfilename, UriKind.Relative);
        //newfilename = uri.AbsolutePath;
        if (!System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(newfilename)))
        {
            try
            {

                Bitmap bmp = new Bitmap(System.Web.HttpContext.Current.Server.MapPath(markerfile));
                Graphics g = Graphics.FromImage(bmp);
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
                StringFormat strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Center;
                SolidBrush myBrush = new SolidBrush(textColor);
                float fontsize = 10;
                bool sizeSetupCompleted = false;
                while (!sizeSetupCompleted)
                {                        
                    SizeF mySize = g.MeasureString(text, new Font("Verdana", fontsize, FontStyle.Bold));
                    if (mySize.Width > 24 || mySize.Height > 13)
                    {
                        fontsize-= float.Parse("0.1");
                    }
                    else
                    {
                        sizeSetupCompleted = true;
                    }
                }

                g.DrawString(text, new Font("Verdana", fontsize, FontStyle.Bold), myBrush, new RectangleF(4, 3, 24, 8), strFormat);
                bmp.Save(System.Web.HttpContext.Current.Server.MapPath(newfilename));
                return newfilename.Substring(2);
            }
            catch (Exception)
            {
                return markerfile.Substring(2);
            }
        }
        return newfilename.Substring(2);
    }

答案 1 :(得分:1)

这是一个快速解决方案:

using (Graphics g = Graphics.FromImage(bmp))
{
    float width = g.MeasureString(text, font).Width;
    float scale = bmp.Width / width;
    g.ScaleTransform(scale, scale); //Simple trick not to use other Font instance
    g.DrawString(text, font, Brushes.Black, PointF.Empty);
    g.ResetTransform();
    ...
}

如果您使用TextRenderingHint.AntiAliasGridFit或类似文字,您的文字将不会始终是100%宽度,但我认为这不是问题,因为您只是想确保文本alawys适合图像。