使用CreateGraphics()在C#中的窗体上绘图 [英] Drawing on Form in C# using CreateGraphics()

查看:178
本文介绍了使用CreateGraphics()在C#中的窗体上绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在C#Form上工作,但是在阅读了有关Graphics类和Draw/Fill方法的文档后,它仍然对我不起作用.

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.

是代码:

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
    }
}

当我按Start(开始)时,将显示一个空表格,没有图纸.你能告诉我我在做什么错吗?

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

推荐答案

您无法在构造函数中绘制图形,因为 OnPaint()方法将在以后由框架调用时将其全部覆盖.

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

相反,覆盖 OnPaint()方法,然后在此处进行绘制.

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

请勿使用 CreateGraphics()创建自己的 Graphics 对象;而是按照我链接的示例,使用通过 e.Graphics 传递给 OnPaint()的代码.

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.

(此外,完成后不要处置 e.Graphics -框架会为您管理.)

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

这篇关于使用CreateGraphics()在C#中的窗体上绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆