我写了bresenham算法
0<Angular coefficient<1
我对 C# 中的图形不太了解,我意识到对于绘制像素我可以使用坐标为 1,1的函数Fillrectangel
我想编写我的代码,然后在面板上单击鼠标并在两个位置画一条从x0,y0 到 xEnd,yEnd的线
所以这是我的代码有异常
空引用异常是未处理的对象引用未设置到对象的实例 此异常在行 e.Graphics.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
我认为问题在于对象 e 是 Null 并且我应该新建它但是如何呢?
如何更正我的代码以绘制线条?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Line l=new Line();
l.LineBres(Cursor.Position.X, Cursor.Position.Y, Cursor.Position.X, Cursor.Position.Y);
}
}
}
public class Line
{
System.Windows.Forms.DrawItemEventArgs e;
Color grad1 = Color.FromArgb(165, 194, 245);
public void LineBres(int x0, int y0, int xEnd, int yEnd)
{
int dx = xEnd - x0;
int dy = yEnd = y0;
int p = 2 * dy - dx;
int twoDy = 2 * dy;
int twoDyMinusDx = 2 * (dy - dx);
int x, y;
if (x0 > xEnd)
{
x = xEnd;
y = yEnd;
xEnd = x0;
}
else
{
x = x0;
y = y0;
}
e.Graphics.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
while (x < xEnd)
{
x++;
if (p < 0)
p += twoDy;
else
{
y++;
p += twoDyMinusDx;
}
e.Graphics.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
}
}
}