【问题标题】:Convert string to font & Color将字符串转换为字体和颜色
【发布时间】:2009-10-05 04:49:34
【问题描述】:

有人可以帮我使用正则表达式(或其他东西)吗,我真的很难完成这项工作,找不到任何可以帮助我完成它的地方。

我有一个程序,用户在表单上放置一些控件。当他们单击保存按钮时,它会遍历表单上的所有控件并将其详细信息保存到文本文件(我知道该怎么做)..就像这样:

Label
"This is text on a label"
20, 97
Tahoma, 7.5, Regular
-778225617

解释:

Control Type
Text property of that control
Location of the control
Font properties for that control
ForeColor for that control.

... 当用户保存它时创建的这个文本文件可能只包含单个控件的信息,如上所示,甚至多个控件,如下所示:

Label
"This is text on a label"
20, 97
Tahoma, 7.5, Regular
-778225617
LinkLabel
"This text belongs to the linklabel text property."
Arial, 20, Bold
-119045893

解释:

Control
Text Property
Location
Font Properties
ForeColor
Control
Text Property
Location
Font Properties
ForeColor

...等等...我发现这对我来说很难,因为到目前为止我还不是专家。有人能帮帮我吗?我还需要将 Font Property 行从字符串转换为 Font 对象,以便在运行时将其分配给指定控件的 Font 属性。

我真的很感激任何帮助。非常感谢。

谢谢 周杰伦

【问题讨论】:

  • 什么环境? winforms/webforms?描述一下您想要进行此类翻译的场景?

标签: c# regex winforms fonts


【解决方案1】:

你会做这样的事情:

using System;
using System.Drawing;

class Example
{
    static void Main()
    {
        String fontName = "Tahoma, Regular, Size";
        String[] fontNameFields = fontName.Split(',');

        Font font = new Font(fontNameFields[0],
            Single.Parse(fontNameFields[2]),
            (FontStyle)Enum.Parse(typeof(FontStyle), fontNameFields[1]));
    }
}

【讨论】:

  • 这当然是假设“Size”实际上是一个浮点数:)
  • 嗨,安德鲁感谢您的回答 :) 在使用上述示例时,我收到一条错误消息,指出索引超出了数组的范围。它到底指的是什么?
  • 这意味着您没有解析包含两个逗号的字符串。调试应用程序并检查包含字体信息的字符串是什么。
【解决方案2】:

您可以从文件中读取文本并将字符串拆分为一个数组,然后使用字体类的重载构造函数来创建新的字体对象。

有关字体构造函数的列表,请参阅

Font Constructor

size 参数是新字体的 em 大小,以 points 为单位。因此,对于其他单位的字体大小,您必须注意这一点。

【讨论】:

    【解决方案3】:

    这似乎是一个表述不佳的问题...我看到其中有几个漏洞。 (我假设您在谈论 WinForms)我稍后会解决这些问题。

    我不知道 .NET 中有什么功能可以为您完成所有这些组合解析。但是,您可以通过使用 CSSName 属性 [它是一个与此属性相近的属性] 使用 WinForms 进行格式调整,并在您的 GUI 上使用 CSS 文件。 [有点奇怪,但它有效]

    顺便说一句,负整数是一个有符号整数,它表示以下颜色集: RGB:

    255 255 255

    问题:

    1. 字体和格式的数据规范似乎表明没有控件可以嵌入另一个控件,这通常通过按钮、标签和带有 WinForms 的面板来完成。 (XML 是嵌入和避免此问题的好建议)
    2. 这不是标准格式。为什么不使用 RTF。使用 RTF,它看起来很简单,您可以让查看器使用它。
    3. 属性定义和值分离。看起来您使用的是属性表格式,不要暗示属性与您的建议一致,它容易解析错误。

    【讨论】:

      【解决方案4】:

      为什么你没有使用 XmlSerialization。您需要做的就是创建一个内存流,并调用它的点 Save 方法;然后您可以随时重新加载数据。

      例如,您有一个名为 Canvas 的类。

      继续像 Canvas.AddControls(controlTypes.Label, "This is text on a label", 20、97、Tahoma、7.5、常规、-778225617);

      请参阅simplest XmlSerializer 示例。

      如果您不希望您的文件是 xml 类型的?使用二进制序列化。 See this.

      类似:

      public static void Save(object obj)
      {
          using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
          {
              // Serialize an object into the storage referenced by 'stream' object.
              System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
      
              // Serialize multiple objects into the stream
              formatter.Serialize(stream, obj);
      
              // If you want to put the stream into Array of byte use below code
              // byte[] buffer = stream.ToArray();
          }
      }
      

      【讨论】:

      • 我以前从未使用过 xmlserializer,我不知道用户将哪些控件添加到画布以保存,也不知道他们将分配什么颜色、大小、字体名称和/或文本到这些控件。所以我不能手动添加这些信息。
      • 请看我下面的评论。
      【解决方案5】:

      10 分钟解决方案:

      好的,接下来的 5 分钟“快速努力”是我真正的意思;我希望这能解决问题。

      • 第 1 步:获取画布 - 画布对象
      • 第 2 步:向其中添加绘图/控件
      • 第 3 步:序列化、保存和重新加载对象

      见下文。

      第 1 步:画布类

      using System;
      using System.Collections.Generic;
      using System.Text;
      using System.IO;
      using System.Xml.Serialization;
      using System.Windows.Forms;
      using System.Runtime.Serialization.Formatters.Binary;
      
      namespace SaveControls
      {
          [Serializable()]
          public class CCanvas
          {
      
              List<CDrawing> _listControls;
          public List<CDrawing> Controls
          {
              get { return _listControls; }
          }
      
          public CCanvas()
          {
              _listControls = new List<CDrawing>();
          }
      
          public void AddControls(CDrawing theControls)
          {
              _listControls.Add(theControls);
          }
      
          public void ReloadControl(Form frm)
          {
              //foreach (CDrawing draw in _listControls) -- requires IEnumerable implementation.
              for (int i = 0; i < _listControls.Count; i++)
              {
                  CDrawing d = (CDrawing)_listControls[i];
                  d.Draw(frm);
              }
          }
      
      
          public void Save()
          {
              try
              {
                  using (Stream stream = File.Open("data.bin", FileMode.Create))
                  {
                      BinaryFormatter bin = new BinaryFormatter();
                      bin.Serialize(stream, this);
                  }
              }
              catch (IOException)
              {
              }
      
          }
      
          public CCanvas Open()
          {
              CCanvas LoadedObj = null;
              using (Stream stream = File.Open("data.bin", FileMode.Open))
              {
                  BinaryFormatter bin = new BinaryFormatter();
      
                  LoadedObj = (CCanvas)bin.Deserialize(stream);
      
              }
              return LoadedObj;
          }
      }
      

      }

      第 2 步:添加图纸

      using System;
      using System.Collections.Generic;
      using System.Text;
      using System;
      using System.Data;
      
      using System.Collections.Generic;
      using System.Collections;
      using System.IO;
      using System.Xml.Serialization;
      using System.Windows.Forms;
      using System.Drawing;
      
      namespace SaveControls
      {
          [Serializable()]
          public class CDrawing
          {
              public enum ControlTypes { Label, TextBox, None };
      
              private ControlTypes _controlType;
          public ControlTypes ControlType
          { get { return _controlType; } }
      
          private string _strControlText;
          public string Text
          { get { return _strControlText; } }
      
          private int _xPosition;
          public int X
          { get { return _xPosition; } }
      
          private int _yPosition;
          public int Y
          { get { return _yPosition; } }
      
      
          private string _strFontName;
          public string Font
          { get { return _strFontName; } }
      
          double _fFontSize;
          public double Size
          { get { return _fFontSize; } }
      
          string _strStyle;
          public string Style
          { get { return _strStyle; } }
      
          decimal _dForegroundColor;
          public decimal Color
          { get { return _dForegroundColor; } }
      
          public CDrawing(ControlTypes controlType, string strControlText, int xPosition, int yPosition,
          string strFontName, double fFontSize, string strStyle, decimal dForegroundColor)
          {
              _controlType = controlType;
              _strControlText = strControlText;
              _xPosition = xPosition;
              _yPosition = yPosition;
              _strFontName = strFontName;
              _fFontSize = fFontSize;
              _strStyle = strStyle;
              _dForegroundColor = dForegroundColor;
      
      
          }
      
          public void Draw(Form frm)
          {
              if (_controlType == ControlTypes.Label)
              {
                  Label lbl = new Label();
      
                  lbl.Text = _strControlText;
                  lbl.Location = new Point(_xPosition, _yPosition);
      
                  System.Drawing.FontStyle fs = (_strStyle == System.Drawing.FontStyle.Regular.ToString()) ? System.Drawing.FontStyle.Regular : System.Drawing.FontStyle.Bold;
      
                  lbl.Font = new System.Drawing.Font(_strFontName, (float)_fFontSize, fs);
                  lbl.ForeColor = SystemColors.Control;// _dForegroundColor;
                  lbl.Visible = true;
                  frm.Controls.Add(lbl);
              }
          }
      
      
      }
      

      }

      第 3 步:使用、序列化、保存、重新加载

      public partial class Form1 : Form
          {
              public Form1()
              {
                  InitializeComponent();
              }
      
      
          public void Save()
          {
              //Create a canvas object
              CCanvas Canvas1 = new CCanvas();
      
              //Add controls
              Canvas1.AddControls(new CDrawing(CDrawing.ControlTypes.Label, "This is text on a label1", 10, 100, "Tahoma", 7.5, "Regular", -778225617));
              Canvas1.AddControls(new CDrawing(CDrawing.ControlTypes.Label, "This is text on a label11", 20, 200, "Verdana", 7.5, "Regular", -778225617));
              Canvas1.AddControls(new CDrawing(CDrawing.ControlTypes.Label, "This is text on a label111", 30, 300, "Times New Roman", 7.5, "Regular", -778225617));
      
              //Save the object
              Canvas1.Save();
          }
      
          private void button1_Click(object sender, EventArgs e)
          {
              Save();
      
          }
      
          private void btnLoad_Click(object sender, EventArgs e)
          {
              Load();
      
          }
      
          public void Load()
          {
              //Retrieve
              CCanvas Canvas2 = new CCanvas();
      
              //opens the binary file
              Canvas2 = Canvas2.Open();
      
              //loads control to this form.
              Canvas2.ReloadControl(this);
      
      
          }
      
      }
      

      如果您打算讨厌此解决方案,请告诉我们原因。同时我正在寻找上传的地方。 Googlecode,但我没有安装颠覆客户端。 :0(

      【讨论】:

      • 如果您想要一个工作的 Windows 窗体解决方案文件,请告诉我。
      • 哦,是的,如果你能把解决方案文件发给我,那就太好了:D
      • 查看我更新的帖子!找不到快速上传的地方。有没有办法在这里上传代码文件
      • 非常感谢克曼!!!该代码完美运行!非常感激!!!!!!!! :D :D :D :D :D
      • 很高兴,我能够提供帮助。快乐编码(0:
      【解决方案6】:

      这对你有用吗?

      Font font = new Font("Tahoma",12,FontStyle.Regular);
      

      【讨论】:

      • 这如何帮助他们从文本文件中解析“Tahoma、Regular、Size”?
      • 如您所见,我在 10 月 5 日回答了这个问题,也就是您编辑问题并添加更多细节的 3 天。您最初的问题没有关于您的文件格式的任何详细信息。
      • 是的,原来的问题确实有足够的细节。
      猜你喜欢
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 2011-03-24
      • 2013-03-21
      • 2011-02-20
      • 2016-02-15
      相关资源
      最近更新 更多