老规矩,先看图:
图1
下面上代码:
1.先画坐标系。盛放的容器为一个size(400,400)的pictureBox。先写一个画坐标轴(箭头)的函数。
int Height = 400, Width = 400;
Pen redArrowPen = new Pen(Color.Black, 1);
private void Axis(int X1,int Y1, int X2, int Y2)//坐标轴
{
System.Drawing.Drawing2D.AdjustableArrowCap lineCap =new System.Drawing.Drawing2D.AdjustableArrowCap(3, 3, true);
redArrowPen.CustomEndCap = lineCap;
Graphics gfx = picBackGround.CreateGraphics();
gfx.DrawLine(redArrowPen, X1, Y1, X2, Y2);
}
2.所谓两点确定一条直线(过两点有且只有一条直线),一次函数的一般表达式为y=ax+b,a、b做输入变量。x用固定变量求解y来确定点。
private int LinearFun(int inPut)
{
if (txtA.Text.Trim()=="")
{
txtB.Text = "1";
}
if (txtB.Text.Trim() == "")
{
txtB.Text = "0";
}
return (Height-(inPut*int.Parse(txtA.Text.Trim())+ int.Parse(txtB.Text.Trim())));
}
3.开始画图。
private void button1_Click(object sender, EventArgs e)
{
Axis(0, Height / 2, Width, Height / 2);//X轴
Axis(Width / 2, Height, Width / 2, 0);//Y轴
Pen pen = new Pen(Color.Blue, 1);
Point Pstart = new Point(-200+ Width / 2, LinearFun(-200) - Height / 2);//起点
Point Pend = new Point(Width/2+ Width / 2, LinearFun(Width / 2) - Height / 2);//终点
Graphics g = picBackGround.CreateGraphics();
g.DrawLine(pen, Pstart, Pend);
int yy = ( (Height/2+ 8)- int.Parse(txtB.Text.Trim())) / int.Parse(txtA.Text.Trim());
g.DrawString("f(x)="+txtA.Text.Trim()+"X+"+txtB.Text.Trim(), new Font("幼圆", 8, FontStyle.Regular), new SolidBrush(Color.Black),yy+190 ,8 );
}