【发布时间】: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<PointF>。当您使用新值调用Calc()时(将来自 TextBox 控件的值传递给方法,已经使用float.TryParse()验证),您重置列表。或者,处理多个List<PointF>,以添加到例如Dictionary<int, List<PointF>>,这样您就可以选择仅重置字典中的一个列表,或者全部重置,或者添加新列表。
标签: c# winforms charts system.drawing