Drawing line without using DrawLine method

1.7k Views Asked by At

Here is my code and I want to implement DDA algorithm without using drawLine method in c# . I tried to use PutPixel method but it did not work . There is nothing in my window. Is there any way to draw line without using drawLine method in c# ?

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        grafik = e.Graphics;

        DDACiz(ilk.X, ilk.Y, ikinci.X, ikinci.Y, grafik, Color.DarkRed);


    }

    void PutPixel(Graphics g, int x, int y, Color c) // sadece bir pixel icin
    {
        System.Drawing.Bitmap bm = new System.Drawing.Bitmap(10, 10);
        bm.SetPixel(0, 0, Color.DarkRed);
        g.DrawImageUnscaled(bm, x, y);
    }

    void DDACiz(int x1, int y1, int x2, int y2,Graphics grafik, Color renk)
    {

        int PikselSayisi;

        int dx, dy;
        float x, xFark;
        float y, yFark;

        dx = x2 - x1;
        dy = y2 - y1;

        PikselSayisi = Math.Abs(dx) > Math.Abs(dy) ? Math.Abs(dx) : Math.Abs(dy);

        xFark = (float)dx / (float)PikselSayisi;
        yFark = (float)dy / (float)PikselSayisi;

        x = (float)x1;
        y = (float)y1;

        while (PikselSayisi!=0)
        {
           PutPixel(grafik,(int)Math.Floor(x + 0.5F),(int) Math.Floor(y + 0.5f),renk);
            x += xFark;
            y += yFark;
            PikselSayisi--;
        }
    }
}
}
1

There are 1 best solutions below

0
On BEST ANSWER

There is no Graphics.DrawPoint method, so to draw a single pixel with a Graphics object you need to use Graphics.FillRectangle

Change

void PutPixel(Graphics g, int x, int y, Color c) // sadece bir pixel icin
{
    System.Drawing.Bitmap bm = new System.Drawing.Bitmap(10, 10);
    bm.SetPixel(0, 0, Color.DarkRed);
    g.DrawImageUnscaled(bm, x, y);
}

to

void PutPixel(Graphics g, int x, int y, Color c) // sadece bir pixel icin
{
    g.FillRectangle(Brushes.DarkRed, x, y, 1, 1);
}

or if you want to use the Color c:

void PutPixel(Graphics g, int x, int y, Color c) // sadece bir pixel icin
{
    using (SolidBrush brush = new SolidBrush(c) )
       g.FillRectangle(brush , x, y, 1, 1);
}

You could also use your appoach of drawing a bitmap but you need to make it either 1x1 pixels wide or make sure it is transparent and also use CompositingMode.SourceOver.

Writing a line draw method is an interesting exercise; much harder than it seems and really tough for PenWidths other than 1.0, let alone for alpha channels other than fully opaque..