new System.Drawing.Font Code Behind

2019-07-09 09:18发布

问题:

I am trying to create an image in c# using a font called Black Rose. The image gets created but not in the font that I want. Here is my code that I used to create the image:

    protected void Page_Load(object sender, EventArgs e)
    {
        string MoneyImg = "1000";
        Bitmap bitmap = new Bitmap(MoneyImg.Length * 40, 150);

        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            Font oFont = new System.Drawing.Font("BLACKR", 20);
            PointF point = new PointF(2f, 2f);
            SolidBrush black = new SolidBrush(Color.Black);
            SolidBrush white = new SolidBrush(Color.White);
            graphics.FillRectangle(white, 0, 0, bitmap.Width, bitmap.Height);
            graphics.DrawString("$" + MoneyImg , oFont, black, point);
        }
    }

I tried changing this line

Font oFont = new System.Drawing.Font("BLACKR", 20);

to

Font oFont = new System.Drawing.Font("BLACKR.TTF", 20);

but is does not make a difference. I know font file is in the correct location because I did a test with CSS Style and it shows up fine. Here is the CSS Code and a screenshot.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
        @font-face 
        { 
        font-family: Black Rose; src: url('BLACKR.TTF'); 
        } 
        h3 {
        font-family: 'Black Rose'
        }
</style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Image ID="Image1" runat="server" />
        <br />
        <h3>This is what the Image Font Looks Like</h3>
    </div>
    </form>
</body>
</html>

回答1:

It's likely that the font simply isn't known to the host system. The file may be somewhere in the web application file hierarchy, but that doesn't make a difference to the underlying system. Windows isn't going to know about a font simply because that font file exists somewhere on the hard drive.

You can add the font to a PrivateFontCollection in code and load it from that. Something like this:

var myFonts = new System.Drawing.Text.PrivateFontCollection();
myFonts.AddFontFile(@"C:\path\to\BLACKR.TTF");
var oFont = new System.Drawing.Font(myFonts.Families[0], 20);


回答2:

This might be wrong as I haven't had time to test it; but since 'BLACKR.TTF' is a custom font, I think you need to add it to a PrivateFontCollection first.



标签: c# css fonts