如何在c#中保存2d形状
本文关键字:保存 2d 形状 | 更新日期: 2023-09-27 18:20:56
我需要在二维空间(x-y坐标)中保存一堆二维形状(定义为定位顶点)。
在c#中最好的方法是什么?
现在我把它们保存为顶点列表:
new Shape()
{
X = 20, //Position of the shape's top left corner on screen
Y = 50, //Position of the shape's top left corner on screen
Vertices = new List<Tuple<float, float>>() //This is a square
{
new Tuple<float, float>(0, 0),//Top left corner
new Tuple<float, float>(0, 100), //Bottom left corner
new Tuple<float, float>(100, 100),//Bottom right corner
new Tuple<float, float>(100, 0)//Top right corner
}
}
public class Shape
{
public float X;
public float Y;
public List<Tuple<float, float>> Vertices;
}
有更好的方法吗?
我需要能够用保存的形状实现两件事:
在屏幕上显示给定的xy坐标(基本上类似于css中的绝对定位)并且知道形状中每个顶点的坐标
您可能想将您的点保存为"实际"点,但除此之外,我认为这无法以任何更好的方式"保存"(也就是说,如果保存意味着将它们存储在内存中)。
看看:
System.Windows.Point
(用于WPF)。或System.Drawing.Point
(适用于WinForms)。
如果你需要将它们保存到磁盘上,你可能想查看一些序列化,你选择的哪种技术最符合你的口味,你需要什么,性能?空间等
ProtoBuf可以用来保存相对较小的文件,同时仍然保持相当不错的性能:https://code.google.com/p/protobuf-net/
或者,您可能想要使用内置的.NET XML序列化程序或二进制序列化程序(请注意,与其他替代程序相比,这些程序通常非常慢)。
此外,如果你想保存一行代码:
public class Shape
{
public Point Position;
public List<Point> Vertices;
}