Использование собственного шрифта TTF для рендеринга изображений DrawString - PullRequest
17 голосов
/ 07 февраля 2009

Я использую 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 ]

32 голосов
/ 07 февраля 2009

Я нашел решение для использования пользовательских шрифтов.

// '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, как и предполагалось.

16 голосов
/ 22 октября 2013

Просто чтобы дать более полное решение

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!");
    } 
}
...