Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

Drawing on Form in C# using CreateGraphics()

I'm trying to get drawing on C# Form working, but after reading documentation about Graphics class and Draw/Fill methods It still doesn't work for me.

It's the code:

using System.Drawing;
using System.Windows.Forms;

namespace Drawing_Example
{
    public partial class Form1 : Form
    {
        #region Constructors

        public Form1()
        {
            InitializeComponent();

            Pen pen = new Pen(Color.Black, 3f);
            Graphics surface = CreateGraphics();
            surface.DrawEllipse(pen, new Rectangle(0, 0, 200, 300));

            pen.Dispose();
            surface.Dispose();
        }

        #endregion Constructors
    }
}

When I press Start an empty form appears, no drawings. Can you tell me what I'm doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot do the drawing in the constructor because the OnPaint() method will overwrite it all when it's called by the framework later.

Instead, override the OnPaint() method and do your drawing there.

Do NOT create your own Graphics object using CreateGraphics(); instead, use the one passed to OnPaint() via e.Graphics as per the example I linked.

(Also, don't dispose e.Graphics when you're done with it - the framework manages that for you.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...