1

我正在尝试以编程方式在 ASP.Net 中创建具有指定字体的位图。这个想法是文本、字体名称、大小颜色等将从变量中传递,并返回使用字体等的文本位图。但是,我发现我只能使用以下代码和某些字体来做到这一点。

   <div>
    <%
     string fontName = "Segoe Script"; //Change Font here
     System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(100, 100);
     System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp);
     System.Drawing.Font fnt = new System.Drawing.Font(fontName, 20);
     System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
    graph.DrawString("Help", fnt, brush, new System.Drawing.Point(10, 10));

    bmp.Save(@"C:\Development\Path\image1.bmp");
    this.Image1.ImageUrl = "http://mysite/Images/image1.bmp";
    %>
 <asp:Label ID="Label1" runat="server" Text="Label" Font-Names="Segoe Script">  <%Response.Write("Help"); %></asp:Label> //Change font here
<asp:Image ID="Image1" runat="server" />
</div>

如果我将注释指示的区域中的字体名称更改为 Arial 或 Verdana,则图像和标签都会以正确的字体显示。但是,如果我将两个位置的字体名称更改为“Segoe Script”,标签将显示在 Segoe Script 中,但图像看起来像 Arial。

更新:

基于这里的这个问题,我能够通过使用 PrivateFontCollection() 并像这样加载字体文件来使其工作。

   <div>
   <%
    string TypeFaceName = "Segoe Script";
    System.Drawing.Text.PrivateFontCollection fnts = new System.Drawing.Text.PrivateFontCollection();
    fnts.AddFontFile(@"C:\Development\Fonts\segoesc.ttf");
    System.Drawing.FontFamily fntfam = new System.Drawing.FontFamily(TypeFaceName);
    System.Drawing.Font fnt = new System.Drawing.Font(fntfam, 13);

    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(100, 100);
    System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp);
    System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
    graph.DrawString("Help", fnt, brush, new System.Drawing.Point(10, 10));

    bmp.Save(@"C:\Development\Path\Images\image1.bmp");
    this.Image1.ImageUrl = "http://MySite/Images/image1.bmp";
    %>
    <asp:Label ID="Label1" runat="server" Text="Label" Font-Names="Segoe Script">     <%Response.Write("Help"); %></asp:Label>
    <asp:Image ID="Image1" runat="server" />
    </div>
4

2 回答 2

1

确保该字体已安装在您的服务器上。

此外,如果两个人同时查看该页面,您的代码将严重失败。
您需要创建一个 .ASHX 处理程序,该处理程序接受查询字符串中的参数并动态提供图像。

于 2010-05-06T14:32:56.083 回答
0

您的代码会遇到内存问题。所有 GDI+ 对象都需要小心释放,否则它们会表现出泄漏行为(即使 GC 最终会通过终结器清理这可能为时已晚,因为未使用的非托管内存量可能会导致应用程序提前中断)。

此外,您可能希望使用特殊的 IHttpHandler 来处理此类“动态文本”的请求,而不是创建“静态”文件。

于 2010-05-06T14:36:14.393 回答