【问题标题】:Cannot create function char using Graphics c#无法使用图形 c# 创建函数 char
【发布时间】:2023-03-07 07:12:01
【问题描述】:

我正在尝试使用图形以特定间隔绘制函数 y = x ^ 2,但我做不到。当我写 start + = 1/10 (以增加点数)时,会消除索引超出数组的错误,在这种情况下,现在的图形看起来并不像它应该的那样。也许有人可以帮助我使用 Graphics 构建此图表。 P.S:是的,我知道我可以使用图表,但任务是通过图形来完成。

using System.Drawing;
using System.Windows.Forms;
namespace FormsForProgrammin
{
    public partial class Form15 : Form
    {
        PointF[] p = new PointF[10];
        int count = 0;
        public Form15()
        {
            InitializeComponent();
            this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form15_Paint);
            Calc();
        }
        private void Calc()
        {
            float start = float.Parse(textBox1.Text);
            while(start<= float.Parse(textBox2.Text))
            {
                float res = start * start;
                p[count] = new PointF(start, res);
                count += 1;
                start += 1;
            }
        }

        private void Form15_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            e.Graphics.TranslateTransform(150, 150);
            e.Graphics.ScaleTransform(1, 0.25F);
            e.Graphics.DrawLines(Pens.Blue, p);
        }
    }
}

【问题讨论】:

  • 不要使用数组,使用List&lt;PointF&gt;。当您使用新值调用 Calc() 时(将来自 TextBox 控件的值传递给方法,已经使用 float.TryParse() 验证),您重置列表。或者,处理多个List&lt;PointF&gt;,以添加到例如Dictionary&lt;int, List&lt;PointF&gt;&gt;,这样您就可以选择仅重置字典中的一个列表,或者全部重置,或者添加新列表。

标签: c# winforms charts system.drawing


【解决方案1】:

您有一个包含 10 个点的数组,并且您正在使用 count 变量对它们进行索引。您在该代码中有几个问题:

  1. 你永远不会重置计数
  2. 您将 start 设置为 textBox1 值,并将其递增 1 直到超过 textBox2 值。但这个差距可能大于你在数组中的点数

要解决 1,您可以在循环完成后重置 count,或者简单地在 Calc 方法本身中定义 count(后者会是更好的选择,因为 count 仅与 Calc 方法相关)

要解决 2,您需要计算步长:值之间的差异除以点数, 使用此步数确保循环运行的次数不超过您拥有的点数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2019-06-18
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    相关资源
    最近更新 更多