2010-05-06 61 views
1

我试图以编程方式在ASP.Net中使用指定字体创建位图。这个想法是,文本,字体名称,大小颜色等将从变量传入,并使用字体等文本的位图将被返回。 但是,我一直在发现,我只能用特定字体使用下面的代码。无法在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脚本”,则该标签将显示在Segoe脚本中,但该图像看起来像Arial。

更新:

基于这个问题here我能得到它的工作通过使用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> 

回答

1

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

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

+0

字体安装在Web服务器上,我可以使用paint.net手动创建带有字体的图像。我发布的代码只是为了查看是否可以完成。谢谢。 – etoisarobot 2010-05-06 15:06:28

0

你会遇到你的代码的内存麻烦。所有GDI +对象都需要小心释放或泄露行为(即使GC最终会通过终结器清理,这可能为时已晚,因为未使用的非管理内存数量可能会导致应用程序更早断开)。

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

相关问题