2009-02-07 20 views
15

के लिए कस्टम टीटीएफ फ़ॉन्ट का उपयोग करना मैं उपयोगकर्ता के ब्राउज़र पर स्ट्रीम की गई छवि बनाने के लिए सर्वर-साइड पर जीडीआई + का उपयोग कर रहा हूं। मानक फोंट से किसी ने मेरे आवश्यकताओं फिट और इसलिए मैं एक ट्रू टाइप फॉन्ट लोड और ग्राफिक्स के लिए अपने तार खींचने के लिए इस फ़ॉन्ट उपयोग करना चाहते हैं वस्तु:DrawString छवि प्रतिपादन

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 कि सर्वर पर स्थापित नहीं है एक फ़ॉन्ट का प्रतिनिधित्व करता है, लेकिन जिसके लिए मेरे पास टीटीएफ फ़ाइल है।

मैं टीटीएफ फ़ाइल कैसे लोड कर सकता हूं ताकि मैं इसे जीडीआई + स्ट्रिंग प्रतिपादन में उपयोग कर सकूं?

उत्तर

31

मुझे कस्टम फ़ॉन्ट्स का उपयोग करने का समाधान मिला है।

// '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 विधि के साथ इस्तेमाल किया जा सकता।

14

बस एक अधिक पूर्ण समाधान

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!"); 
    } 
} 
देने के लिए
संबंधित मुद्दे