我正在尝试以编程方式在 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>