代码之家  ›  专栏  ›  技术社区  ›  Llyle

使用自定义的TTF字体进行抽绳图像渲染

  •  17
  • Llyle  · 技术社区  · 17 年前

    我正在服务器端使用gdi+创建一个图像,该图像被流式传输到用户的浏览器。没有一种标准字体符合我的要求,因此我希望加载TrueType字体,并使用此字体将字符串绘制到图形对象:

    using (var backgroundImage = new Bitmap(backgroundPath))
    using (var avatarImage = new Bitmap(avatarPath))
    using (var myFont = new Font("myCustom", 8f))
    {
        Graphics canvas = Graphics.FromImage(backgroundImage);
        canvas.DrawImage(avatarImage, new Point(0, 0));
    
        canvas.DrawString(username, myFont,
            new SolidBrush(Color.Black), new PointF(5, 5));
    
        return new Bitmap(backgroundImage);
    }
    

    myCustom 表示服务器上未安装但有TTF文件的字体。

    如何加载TTF文件以便在gdi+字符串呈现中使用它?

    2 回复  |  直到 11 年前
        1
  •  32
  •   Jay Riggs    14 年前

    我找到了使用自定义字体的解决方案。

    // 'PrivateFontCollection' is in the 'System.Drawing.Text' namespace
    var foo = new PrivateFontCollection();
    // Provide the path to the font on the filesystem
    foo.AddFontFile("...");
    
    var myCustomFont = new Font((FontFamily)foo.Families[0], 36f);
    

    现在 myCustomFont 可与graphics.drawstring方法一起使用。

        2
  •  16
  •   user890255    12 年前

    只是为了给出一个更完整的解决方案

    using System;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Drawing;
    using System.Drawing.Text;
    
    public partial class Test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string fontName = "YourFont.ttf";
            PrivateFontCollection pfcoll = new PrivateFontCollection();
            //put a font file under a Fonts directory within your application root
            pfcoll.AddFontFile(Server.MapPath("~/Fonts/" + fontName));
            FontFamily ff = pfcoll.Families[0];
            string firstText = "Hello";
            string secondText = "Friend!";
    
            PointF firstLocation = new PointF(10f, 10f);
            PointF secondLocation = new PointF(10f, 50f);
            //put an image file under a Images directory within your application root
            string imageFilePath = Server.MapPath("~/Images/YourImage.jpg");
            Bitmap bitmap = (Bitmap)System.Drawing.Image.FromFile(imageFilePath);//load the image file
    
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                using (Font f = new Font(ff, 14, FontStyle.Bold))
                {
                    graphics.DrawString(firstText, f, Brushes.Blue, firstLocation);
                    graphics.DrawString(secondText, f, Brushes.Red, secondLocation);
                }
            }
            //save the new image file within Images directory
            bitmap.Save(Server.MapPath("~/Images/" + System.Guid.NewGuid() + ".jpg"));
            Response.Write("A new image has been created!");
        } 
    }