将双精度值转换为Point类型

8
我希望能使用bitmap图像在picturebox中绘制曲线(二极管曲线)。但是我现在有一个问题,我的点数据保存为Double类型,保留精度非常重要。
例如,我拥有的绘图中的一个点如下所示:
电压:-0.175 电流:-9.930625E-06
是的,它是一个Double类型!那么我该如何获得一个点来进行绘制呢?
        Point[] ptarray = new Point[3];
        ptarray[0] = new Point(250, 250);

有没有接受双精度值的Point[]替代品?我有一个500x500像素的图片框。有没有一种方法可以将这些值转换为有效的点,同时仍然保留精度?我正在使用微安培(10^-6)和电压!

3个回答

15

如果 float 的精度足够,那么你可以使用 PointF 结构体

var point = new PointF(3.5f, 7.9f);

如果确实需要的话,你可以定义自己的 PointD 结构体:

public struct PointD {
    public double X;
    public double Y;

    public PointD(double x, double y) {
        X = x;
        Y = y;
    }

    public Point ToPoint() {
        return new Point((int)X, (int)Y);
    }

    public override bool Equals(object obj) {
      return obj is PointD && this == (PointD)obj;
    }
    public override int GetHashCode() {
      return X.GetHashCode() ^ Y.GetHashCode();
    }
    public static bool operator ==(PointD a, PointD b) {
      return a.X == b.X && a.Y == b.Y;
    }
    public static bool operator !=(PointD a, PointD b) {
      return !(a == b);
    }
}

这里的等式代码最初来自这里

ToPoint()方法可以让你将其转换为一个Point对象,当然精度会被截断。


请参考 https://dev59.com/Bm435IYBdhLWcg3wxDL_#5221407 获取结构体的正确 GetHashCode() - John Alexiou

1

如果只是为了存储这些值,总有 Tuple可用:

Tuple<double, double>[] Points = new Tuple<double, double>[50];
Points[0] = Tuple.Create<double, double>(5.33, 12.45);

1
元组不添加任何上下文,而且过于通用,使代码难以阅读。我建议将它们作为最后的选择。 - vidstige

0

尽管System.Drawing.Point结构使用int值,而System.Drawing.PointF结构使用float值,但也有System.Windows.Point结构,它使用double值。因此,如果float不能提供足够的精度,这可能是您最好的选择。

然而,由于该结构的名称与基于int的结构的名称冲突,在已经有using System.Drawing指令的文件中使用它可能会很麻烦:

using System.Drawing;
...
System.Windows.Point coords = new System.Windows.Point(1.5, 3.9);

幸运的是,您可以通过使用别名来解决这个问题:

using System.Drawing;
using PointD = System.Windows.Point;
...
PointD coords = new PointD(1.5, 3.9);

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