将字体转换为字符串并再次返回
我有一个应用程序,我的用户更改不同标签等的字体和字体颜色,他们将其保存到文件但我需要能够将指定标签的字体转换为要写入文件的字符串,然后当他们打开该文件,我的程序将该字符串转换回字体对象。 如何才能做到这一点? 我还没有找到任何能说明如何做到的事情。
谢谢
巴尔
使用System.Drawing.FontConverter类可以很容易地从字体到字符串来回返回。 例如:
var cvt = new FontConverter(); string s = cvt.ConvertToString(this.Font); Font f = cvt.ConvertFromString(s) as Font;
您可以将字体类序列化为文件。
有关如何执行此操作的详细信息,请参阅此MSDN文章 。
要序列化:
private void SerializeFont(Font fn, string FileName) { using(Stream TestFileStream = File.Create(FileName)) { BinaryFormatter serializer = new BinaryFormatter(); serializer.Serialize(TestFileStream, fn); TestFileStream.Close(); } }
并反序列化:
private Font DeSerializeFont(string FileName) { if (File.Exists(FileName)) { using(Stream TestFileStream = File.OpenRead(FileName)) { BinaryFormatter deserializer = new BinaryFormatter(); Font fn = (Font)deserializer.Deserialize(TestFileStream); TestFileStream.Close(); } return fn; } return null; }
如果你想让它在文件中可读,真的很简单:
class Program { static void Main(string[] args) { Label someLabel = new Label(); someLabel.Font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Strikeout | FontStyle.Italic); var fontString = FontToString(someLabel.Font); Console.WriteLine(fontString); File.WriteAllText(@"D:\test.txt", fontString); var loadedFontString = File.ReadAllText(@"D:\test.txt"); var font = StringToFont(loadedFontString); Console.WriteLine(font.ToString()); Console.ReadKey(); } public static string FontToString(Font font) { return font.FontFamily.Name + ":" + font.Size + ":" + (int)font.Style; } public static Font StringToFont(string font) { string[] parts = font.Split(':'); if (parts.Length != 3) throw new ArgumentException("Not a valid font string", "font"); Font loadedFont = new Font(parts[0], float.Parse(parts[1]), (FontStyle)int.Parse(parts[2])); return loadedFont; } }
否则序列化是要走的路。
首先,您可以使用以下文章枚举系统字体。
public void FillFontComboBox(ComboBox comboBoxFonts) { // Enumerate the current set of system fonts, // and fill the combo box with the names of the fonts. foreach (FontFamily fontFamily in Fonts.SystemFontFamilies) { // FontFamily.Source contains the font family name. comboBoxFonts.Items.Add(fontFamily.Source); } comboBoxFonts.SelectedIndex = 0; }
要创建字体:
Font font = new Font( STRING, 6F, FontStyle.Bold );
用它来设置字体样式等….
Label label = new Label(); . . . label.Font = new Font( label.Font, FontStyle.Bold );
使用此代码根据名称和颜色信息创建字体:
Font myFont = new System.Drawing.Font(, 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); Color myColor = System.Drawing.Color.FromArgb();