我有一个学校项目,我必须有一个功能,可以从屏幕上的任何地方画线到屏幕上的任何其他地方。我知道有一些功能可以帮助我。
这就是我到目前为止:( vga.setpixel事物设置(uint)x像素,在(uint)y像素,颜色(uint)颜色)
class drawaline
{
public static void swap(ref int a, ref int b)
{
int temp = a; // Copy the first position's element
a = b; // Assign to the second element
b = temp; // Assign to the first element
}
public static int abs(int value)
{
if (value < 0)
value = value * -1;
return value;
}
public static int fpart(int x)
{
return x;
}
public static int rfpart(int x)
{
x = 1 - fpart(x);
return x;
}
public static int ipart(int x)
{
return x;
}
public static void line(int x1, int y1, int x2, int y2, uint color)
{
int dx = x2 - x1;
int dy = y2 - y1;
if (abs(dx) < (dy))
{
swap(ref x1, ref y1);
swap(ref x2, ref y2);
swap(ref dx, ref dy);
}
if (x2 < x1)
{
swap(ref x1, ref x2);
swap(ref y1, ref y2);
}
int gradient = dy / dx;
// handle first endpoint
int xend = x1;
int yend = y1 + gradient * (xend - x1);
int x1p = x1 + (int).5;
int xgap = rfpart(x1p);
int xpxl1 = xend; // this will be used in the main loop
int ypxl1 = ipart(yend);
VGAScreen.SetPixel320x200x8((uint)xpxl1, (uint)ypxl1, (uint)color);
int intery = yend + gradient; // first y-intersection for the main loop
// handle second endpoint
xend = x2;
yend = y2 + gradient * (xend - x2);
xgap = fpart(x2 + (int)0.5);
int xpxl2 = xend; // this will be used in the main loop
int ypxl2 = ipart(yend);
VGAScreen.SetPixel320x200x8((uint)xpxl2, (uint)ypxl2, (uint)color);
VGAScreen.SetPixel320x200x8((uint)xpxl2, (uint)ypxl2 + 1, (uint)color);
// main loop
for (x = 0; x < xpxl1 + 1; x++)
{
VGAScreen.SetPixel320x200x8((uint)x, (uint)intery, (uint)color);
VGAScreen.SetPixel320x200x8((uint)x, (uint)intery, (uint)color);
intery = intery + gradient;
}
}
}
答案 0 :(得分:1)
许多错误:
swap
需要将其参数设为ref
Math.Abs
而不是自己编写(技术上不是错误,但风格不好)fpart
函数很可能无法执行您想要的操作。我认为它应该返回double
的小数部分,而不是传入的int
。让它接受并返回double
。(int)0.5
没有意义。它变为0。int
变量应该是双倍的。由于您的代码假定它们可以包含非整数。int gradient = dy / dx
使用整数除法。你需要在分割之前将其中一个加注成双倍,否则你将失去小数部分。答案 1 :(得分:0)
有一个icon.cs文件,其中包含您想要的代码
答案 2 :(得分:0)
void draw_line()
{
Pen mypen;
mypen = new Pen(Color.Black , 1);
Graphics g = this.CreateGraphics();
g.DrawLine(mypen, 0, 20, 1000, 20);
// 0,20 are starting points and 1000,20 are destination.
mypen.Dispose();
g.Dispose();
}