如何在C#中缩放和绘制绘图

时间:2011-10-31 15:33:47

标签: c# winforms graphics bitmap plot

我正在尝试使用下面的CSV绘制图表:

2.364258,3.005366
2.723633,3.009784
3.083008,3.012145
3.442383,3.012705
3.801758,3.010412
4.160156,3.010703
4.518555,3.011985
4.876953,3.012547
5.235352,3.009941
5.592773,3.011252
5.951172,3.010596
6.30957,3.011951
6.667969,3.010613
7.026367,3.008634
7.384766,3.009744
7.743164,3.01062
8.101563,3.00942
8.459961,3.009438
8.818359,3.009478
9.177734,3.010827

到目前为止我所做的是我试图让一个班级做到这一点!这是我尝试绘制曲线的部分:

class Plotter
    {
        #region Fields and variables

        private Bitmap plot;
        private Graphics g;

        public string PlotType {get; set;}        

        private int iWidth; //Width of the box
        private int iHeight; //

        private float xMax; //maximum range on X axis
        private float yMax; //maximum range on Y axis

        private PointF[] points;

        #endregion    

        #region Constructors

        /// <summary>
        /// Constructor of class
        /// </summary>
        /// <param name="iWidth">Width of image in pixels</param>
        /// <param name="iHeight">Height of image in pixels</param>
        /// <param name="xMax">Maximum value of the values on X</param>
        /// <param name="yMax">Maximum value of the values on Y</param>
        /// <param name="pairs">Pairs of data in an array of PointF[] this is raw data!!</param>
        public Plotter(int iWidth, int iHeight, float xMax, float yMax, PointF[] points)
        {
            this.iWidth = iWidth;
            this.iHeight = iHeight;
            this.xMax = xMax;
            this.yMax = yMax;

            this.points = points;

            plot = new Bitmap(iWidth, iHeight); 
        }

        public Bitmap DrawPlot()
        {
            Pen blackPen = new Pen(Color.Black, 1);
            g = Graphics.FromImage(plot);

            PointF[] p = new PointF[points.GetLength(0)];

            //Try to scale input data to pixel coordinates
            foreach (PointF point in points)
            {
                int i = 0;

                p[i].X = point.X * iWidth;
                p[1].X = point.Y * iHeight;

            }

            g.DrawCurve(blackPen, p, 0);

            return plot;
        }

我最后得到的是一条直线!我认为已经在X {0,0}和Y {0,0}上绘制了X {0,400}和Y {0,0}

你能帮我纠正错误吗?

P.S:http://itools.subhashbose.com/grapher/index.php这个网站可以从我拥有的CSV数据中绘制出我需要相当不错的情节(如果你需要检查)。

谢谢!

2 个答案:

答案 0 :(得分:3)

这似乎是你的问题:

foreach (PointF point in points)
{
  int i = 0;

  p[i].X = point.X * iWidth;
  p[1].X = point.Y * iHeight;
}

i始终为零,您永远不会分配Y。 “第二个”赋值甚至不使用i,而是使用1个索引。

无需错误检查即可快速修复:

int i = 0;
foreach (PointF point in points)
{
  p[i].X = point.X * iWidth;
  p[i].Y = point.Y * iHeight;

  i++;
}

答案 1 :(得分:1)

你两次分配x。

   p[i].X = point.X * iWidth;
   p[1].X = point.Y * iHeight;

正如@LarsTech指出你需要修理计数器