【问题标题】:save width and color of stroke to bytearray将笔画的宽度和颜色保存到字节数组
【发布时间】:2016-03-17 20:29:38
【问题描述】:

我正在将笔画保存到数据库中,我可以检索它们。现在我还想保存笔画的颜色、宽度和透明度。

这就是我的代码中的内容

private void AddFloorPlan()
{
     MyCustomStrokes customStrokes = new MyCustomStrokes();
     customStrokes.StrokeCollection = new Point[FloorPlanStrokes.Count][];
     for (int i = 0; i < FloorPlanStrokes.Count; i++)
     {
         customStrokes.StrokeCollection[i] =
         new Point[FloorPlanStrokes[i].StylusPoints.Count];
         for (int j = 0; j < FloorPlanStrokes[i].StylusPoints.Count; j++)
         {
             customStrokes.StrokeCollection[i][j] = new Point();
             customStrokes.StrokeCollection[i][j].X = FloorPlanStrokes[i].StylusPoints[j].X;
             customStrokes.StrokeCollection[i][j].Y = FloorPlanStrokes[i].StylusPoints[j].Y;
         }
     }
     MemoryStream ms = new MemoryStream();
     BinaryFormatter bf = new BinaryFormatter();
     bf.Serialize(ms, customStrokes);

     byte[] bytes = ms.ToArray();
     ms.Dispose();
}

[Serializable]
public sealed class MyCustomStrokes
{
    public MyCustomStrokes() { }
       /// <SUMMARY>
       /// The first index is for the stroke no.
       /// The second index is for the keep the 2D point of the Stroke.
       /// </SUMMARY>
    public Point[][] StrokeCollection;
}

【问题讨论】:

    标签: c# wpf drawing stroke inkcanvas


    【解决方案1】:

    将颜色信息存储为stringColor.ToString() 完成工作)并在反序列化时将其转换为Color,如下所示:

    (Color)ColorConverter.ConvertFromString(STORED_STRING);
    

    如果以后不更改颜色,您将创建新的BrushFreeze

    宽度 (StrokeThickness?) 是另一回事。只需将其另存为double即可。

    例子:

    [Serializable]
    public sealed class MyCustomStrokes
    {
        public string[][] ColorCodeCollection;
    
        [NonSerialized()]
        private Dictionary<string, SolidColorBrush> _memo;
        public Brush GetBrush(int i, int j) 
        {
            var code = ColorCodeCollection[i][j];
            if(_memo.ContainsKey(code))
                return _memo[code];
    
            var col = (Color)ColorConverter.ConvertFromString(code);
            var brush = new SolidColorBrush(col);
            brush.Freeze();
            _memo[code] = brush;
            return brush;
        }
    }
    

    请注意,这只是一个快速代码。检查它是否符合您的计划。

    【讨论】:

    • 感谢您为我指明了正确的方向,但我对 C# 还是很陌生。那么现在如何将其放入现有代码中?
    • 已编辑答案以显示仅恢复画笔的示例,因为我不知道颜色是如何确定的。没有异常处理和可能的不良做法,但超出了范围。
    猜你喜欢
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多