How to draw lines in c#
i have a school project where i have to have a function that can draw a line from anywhere on the screen to anywhere else on the screen. i know that there are some functions included that do it for me.
this is what i have so far: (the vga.setpixel thing sets the (uint)x pixel, at the (uint)y pixal, the color (uint) color)
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;
}
}
}
Many mistakes:
swap
needs to take its parameters asref
- There is
Math.Abs
which you can use instead of writing your own(Technically not a mistake but bad style) - Your
fpart
function most likely doesn't do what you want it to do. I assume it should return the fractional part of adouble
and not theint
passed in. Make it take and return adouble
. (int)0.5
doesn't make sense. It becomes 0.- Most of your
int
variables should be double instead. Since your code assumes that they can contain non integral numbers. int gradient = dy / dx
uses integer division. You need to cast one of them to double before dividing or you lose the fractional part.
Check this it will help you
there is an icon.cs file which contains the code you want
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();
}
精彩评论