在c#中绘制二次方程曲线

时间:2015-02-09 07:54:31

标签: c# quadratic-curve

我是c#System Draw的新手,所以请帮我解决我的代码问题。我试图绘制二次方程曲线,并使用" for"循环以便为曲线点10坐标。我已多次测试此代码,并且在启动代码时没有任何内容出现。每当我运行代码时,我得到消息ArgumentException是Unhandled,参数对代码无效" g.DrawCurve(aPen,Points);"突出显示。请帮我解决这个问题,我花了很多天试图修复。

{
    public Form1()
    {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs e)
    {

        float a = 10, b = 30, c = 10;
        double x1, x2, delta, cx1, cx2, y1, y2;
        int icx1, iy1, icx2, iy2;
        delta = (b * b) - (4 * a * c);
        x1 = ((b * (-1)) + Math.Sqrt(delta)) / (2 * a);
        x2 = ((b * (-1)) - Math.Sqrt(delta)) / (2 * a);
        for (int i = (-10); i <= 10; i = i + 1)
        {
            cx1 = i * x1;
            cx2 = i * x2;
            y1 = (cx1 * cx1 * a) + (cx1 * b) + c;
            y2 = (cx2 * cx2 * a) + (cx2 * b) + c;
            icx1 = Convert.ToInt32(cx1);
            iy1 = Convert.ToInt32(y1);
            icx2 = Convert.ToInt32(cx2);
            iy2 = Convert.ToInt32(y2);


            Graphics g = e.Graphics;
            Pen aPen = new Pen(Color.Blue, 1);
            Point point1 = new Point(icx1, iy1);
            Point point2 = new Point(icx2, iy2);
            Point[] Points = { point1,point2 };
            g.DrawCurve(aPen, Points);
            aPen.Dispose();
            g.Dispose();


        }

2 个答案:

答案 0 :(得分:4)

关键问题是代码处理Graphics对象。在第二次迭代中,已经放置了Graphics对象,并且对DrawCurve的调用将失败。

正如评论中所提到的,DrawCurve方法需要数组中的3个点。请参阅MSDN Page for DrawCurve

上的备注

应尽可能减少对Pen的所有其他Dispose调用,以防止重新创建如此多的笔。

至于图:我不完全确定你要做什么,但是如果你想绘制一个抛物线,你不应该求解二次方程,而是把x值放在等式中。

伪代码:

for x = -10 to 10 step 3

    if SavePoint == null

        x1 = x
        y1 = a * x1 * x1 + b * x1 + c

        point1 = TransformToLocalCoordinates(x1, y1)

    Else

        point1 = SavePoint

    End if

    x2 = x + 1
    y2 = a * x2 * x2 + b * x2 + c

    point2 = TransformToLocalCoordinates(x2, y2)

    x3 = x + 2
    y3 = a * x3 * x3 + b * x3 + c

    point3 = TransformToLocalCoordinates(x3, y3)

    DrawCurve point1, point2, point3

    SavePoint = point3

next

答案 1 :(得分:1)

不要处置GraphicsPen个实例 - 你正在循环的每一步都这样做。

相反,获取Pen的一个实例(并注意您可以使用全局Pens.Blue :)),并且不要丢弃它或Graphics对象。

另外,尝试使用DrawLine代替DrawCurve作为开始 - 它不会给你很好的抗锯齿图,但它更容易。一旦你理解了如何正确使用它,只能从DrawCurve开始:)其中一点是你不能仅通过两点来绘制它 - 你需要至少三个。

DrawCurve在所有指定点绘制样条线。所以实际上,你只能调用它一次,你预先计算出的二次方的所有点。这将为您提供一个很好的渲染曲线。但是,我不确定它是否真的是一个真正的二次方 - 我不确定GDI +的样条是二次的还是(更有可能)立方。在任何情况下,它都不适用于不同曲线的精确渲染。

相关问题