开发者

How do I get a Font from a string?

In the the System.Web.UI.DataVisualization.Charting.Chart control a font can be set by referring Font by it's family name. How do I do something similar in code?

 <asp:Chart runat="server">
     <legends>
         <asp:Legend Font="Microsoft Sans Serif, 8.25pt, style=Bold"/>
     </legends>
 </asp:Chart>

How can开发者_JS百科 I do something similar in the codebehind?

chart.Legends[0].Font = Font.???("Microsoft Sans Serif, 8.25pt, style=Bold")


Use one of the constructors on the System.Drawing.Font class:

chart.Legends[0].Font = new Font("Microsoft Sans Serif", 
                                 8.25,
                                 FontStyle.Bold);

Make sure to include System.Drawing to get easy access to all the related items (FontFamily, FontStyle, etc).


You might be able to parse it, assuming it always came in in that form:

string[] fontStrings = "Microsoft Sans Serif, 8.25pt, style=Bold".Split(',');
fontStrings[1] = fontStrings[1].Replace("pt", "");
fontStrings[2] = fontStrings[2].Replace("style=", "");
var font = new System.Drawing.Font(
  fontStrings[0],
  float.Parse(fontStrings[1]),
  ((FontStyle)Enum.Parse(typeof(FontStyle), fontStrings[2]))
);

EDIT: Ah, I did it the hard way. If it's not dynamic, the other answers are signficantly nicer than my string-munging. :)


Use the following overload of the System.Drawing.Font constructor:

chart.Legends[0].Font = new Font("Microsoft Sans Serif", 8.25, FontStyle.Bold);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜