简体   繁体   中英

C# Graphics.Drawline function not working, “The name 'graphics' does not exist in the current context”

I am creating my first visual C# program. I am trying to get to grips with drawing graphs/lines, however I am getting the error "the name 'graphics' does not exist in the current context".

This is the entirety of my program:

public Form1()
{

    InitializeComponent();

    Pen blackPen = new Pen(Color.Black, 3);

    Point point1 = new Point(100, 100);
    Point point2 = new Point(500, 100);

    graphics.DrawLine(blackPen, point1, point2);
}

Google tells me that the graphics.DrawLine function is within the System.Drawing namespace that I have already included.

Apologies if this is a simple question as this is very much my "hello world".

You could add an event handler to Paint event of the form, having code something like below:

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Pen redPen = new Pen(Color.Red, 30);

        Point point1 = new Point(0, 0);
        Point point2 = new Point(500, 500);

        e.Graphics.DrawLine(redPen, point1, point2);

        redPen.Dispose();
    }

And not trying to do the drawing in the form constructor. So move the code from the constructor to this event handler.

You're probably working from examples you've seen online where the Graphics object is provided as a parameter to a method or defined outside of the code shown. Graphics objects can draw to a variety of targets--the screen, an image, a printer.... You should figure where you want your graphics to go; how to initialize or get a reference to the appropriate Graphics object will depend on this. For instance, if you want a simple way to draw to the screen, add a Paint event handler to a Form via the Windows Forms Designer. When the event fires, you'll get a PaintEventArgs object that has a property called Graphics . Use this to do your drawing.

You're declaring Graphics as a local variable within your constructor. You probably would rather declare it as an instance first, then assign it inside the constructor.

The issue appears to be that you haven't declared the graphics variable. I think you need something like:

public Form1() {
    InitializeComponent();

    Pen blackPen = new Pen(Color.Black, 3);

    Point point1 = new Point(100, 100);
    Point point2 = new Point(500, 100);

    Graphics graphics = CreateGraphics();
    graphics.DrawLine(blackPen, point1, point2);
}

The extra line here creates a new graphics object on the current form which you can use to draw the line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM