Search code examples
c#gdi

How to draw a moving line in an image


I am trying to draw a horizontal line on the white rectangle corresponding to the cursor position on it.

public static void CreateMapHistoGramModifiedByColourBar(int LineYindex)
{
    float[] dashValues = { 1, 1, 1 };
    Pen blackPen = new Pen(Color.Black, 1);
    blackPen.DashPattern = dashValues;
    Point P1 = new Point(0, LineYindex);
    Point P2 = new Point(RefBarWidth, LineYindex);
    using (Graphics g = Graphics.FromImage(Image.FromFile(WaferMapHistogramFileName)))
    {
        g.DrawLine(blackPen, P1, P2);
    }
}

The above code does not seem to be doing anything to the saved image. How can I solve this issue?


Solution

  • Judging on this line:

    the above mentioned code does not seem to be doing anything to the saved image

    It sounds like you want to draw a line on the image and then save that new image back out. At the moment all you are doing is loading in an Image object, drawing on that and then discarding of it:

    using (Graphics g = Graphics.FromImage(Image.FromFile(WaferMapHistogramFileName)))
    {
        g.DrawLine(blackPen, P1, P2);
    }
    

    Note that the Image class also implements IDisposable so you should be disposing of it.

    Put all this together and you should get something like this:

    using (Image image = Image.FromFile(WaferMapHistogramFileName))
    using (Graphics g = Graphics.FromImage(image))
    {
        g.DrawLine(blackPen, P1, P2);
    
        image.Save(@"Save somewhere, here: WaferMapHistogramFileName?");
    }
    

    Note that saving the image back at WaferMapHistogramFileName will overwrite the original.


    Side note; from this line:

    corresponding to the cursor position

    Your drawing a line on the image judging by the position of the cursor on it. If this is the case you should make sure you are offsetting the cursor position as that will give you its location on the Screen, Form or Control.