将字符串转换为字体和颜色

3

请问有人可以帮助我写一个正则表达式(或者其他的方法),我真的很难完成这个任务,也找不到任何能帮助我完成它的资料。

我有一个程序,在这个程序中用户可以在一个表单上放置一些控件。当他们点击保存按钮时,程序将遍历表单上的所有控件,并将它们的详细信息保存到一个文本文件中(我知道如何实现)...就像这样:

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属性。

我会非常感激任何形式的帮助。非常感谢。

谢谢 jay


什么环境?WinForms/WebForms?请描述您希望进行此类翻译的场景。 - shahkalpesh
6个回答

3
您需要做的是这样的:

您需要像这样做:

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”实际上是一个浮点数 :) - Andrew Hare
嗨,安德鲁,谢谢你的回答 :) 当我使用上面的示例时,我遇到了一个错误,它说索引超出了数组的范围。它具体指的是什么? - jay_t55
这意味着您没有解析包含两个逗号的字符串。调试应用程序并检查包含字体信息的字符串是什么。 - Andrew Hare

1

为什么你不使用XmlSerialization呢?你只需要创建一个内存流,调用它的Save方法,然后你可以在任何时候重新加载数据。

比如你有一个叫做Canvas的类。

像这样做:Canvas.AddControls(controlTypes.Label, "This is text on a label", 20, 97, Tahoma, 7.5, Regular, -778225617);

请查看 最简单的XmlSerializer示例。

如果你不想让文件是xml类型?使用二进制序列化。看这里

类似这样:

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();
    }
}

我以前从未使用过XML序列化器,也不知道用户将添加哪些控件到画布中以进行保存,更不知道他们将为这些控件分配什么颜色、大小、字体名称和/或文本。因此,我不能手动添加此信息。 - jay_t55
请看我的下面评论。 - KMån

1

你可以从文件中读取文本,将其拆分为数组,然后使用字体类的重载构造函数创建新的字体对象。

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

字体构造函数

大小参数是新字体的点数。因此,对于其他单位的字体大小,您需要特别注意。


1

这个问题似乎表述不清楚...我看到了一些漏洞。(我假设你在谈论WinForms) 我稍后会解决这些问题。

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

顺便说一下,那个负数整数表示颜色集:

RGB:

255 255 255

问题:

  1. 字体和格式的数据规范似乎表明没有控件可以嵌入另一个控件,但在WinForms中经常使用按钮、标签和面板进行嵌入。(XML将是一个很好的建议,以避免这个问题)
  2. 这不是标准格式。为什么不使用RTF。使用RTF似乎很简单,并且您还可以获得一个查看器。
  3. 属性定义和值分离。看起来您正在使用属性表格格式,请不要暗示属性与您建议的内容相匹配,否则解析容易出错。

0

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);
        }
    }


}

}

步骤三:使用、序列化、保存、重新加载

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,但是我没有安装Subversion客户端。 :0(


请告诉我是否需要一个可工作的Windows窗体解决方案文件。 - KMån
哦,是的,如果你能给我发送解决方案文件,那就太棒了!:D - jay_t55
看到我的更新帖子!找不到快速上传的地方。这里没有上传代码文件的方法吗? - KMån
非常感谢Kman!!! 那段代码完美地运行了!非常感激!!!!!!!! :D :D :D :D :D - jay_t55
1
很高兴能够帮到你。愉快编程!(0: - KMån

-1

这个对你有用吗?

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

3
他们如何从文本文件中解析出"Tahoma, Regular, Size",这会对他们有什么帮助? - Andrew Hare
正如您所看到的,我在10月5日回答了这个问题,在您编辑问题并添加更多细节之前的3天。您最初的问题没有提供有关文件格式的任何详细信息。 - Andrew Keith
是的,原始问题已经提供了足够的细节。 - anon271334

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接