简体   繁体   中英

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 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. :)

使用System.Drawing.Font构造函数的以下重载:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM