C#画线OnPaint()与CreateGraphics() [英] C# Draw Line OnPaint() vs CreateGraphics()

查看:318
本文介绍了C#画线OnPaint()与CreateGraphics()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题: 您如何通过OnPaint()方法以外的其他方法正确绘制Winform?

Question: How do you properly draw on a winform from a method other than the OnPaint() method?

其他信息: 我现在使用的代码在OnPaint()方法中为TicTacToe游戏绘制了一些背景线.然后,我使用Mouse_Click事件并运行此代码,这显然是不合适的:

Additional Information: The code I have now draws some background lines for a TicTacToe game in the OnPaint() method. Then I use the Mouse_Click event and am running this code which apparently is not proper:

private void TicTacToe_MouseClick(object sender, MouseEventArgs e)
   Graphics g = this.CreateGraphics();
   g.DrawEllipse(this.penRed, this.Rectangle);

出于我不明白的原因,它确实绘制了圆圈,但是当最小化或将窗体移出屏幕时,它会擦除​​圆圈,但不会擦除OnPaint()方法中的线条.

For reasons I do not understand, it does draw the circle, but when minimizing or moving the form off screen it erases the circles but not the lines from the OnPaint() method.

推荐答案

您正在做的是异步"绘制表单(来自OnPaint方法).您会看到,OnPaint方法是Windows窗体绘制整个窗体所依赖的方法.当您的发件人"发生故障时,它会失效,并再次调用OnPaint.如果在该方法中未绘制任何内容,则在发生这种情况后,该内容将不再存在.

What you are doing is drawing on the form "asynchronously" (from the OnPaint method). You see, the OnPaint method is what Windows Forms relies on to draw your entire form. When something happens to your From, it is invalidated and OnPaint is called again. If something isn't drawn in that method, then it will not be there after that happens.

如果您希望按钮触发某些东西永久显示,那么您需要做的就是将该对象添加到某个地方的集合中,或设置一个与之相关的变量.然后调用Refresh(),后者调用Invalidate()和Update(),然后在OnPaint期间绘制该对象(椭圆形).

If you want a button to trigger something to appear permanently then what you need to do is Add that object to a collection somewhere, or set a variable related to it. Then call Refresh() which calls Invalidate() and Update() Then, during OnPaint, draw that object (ellipis).

如果您希望它在表单发生问题(例如最小化)后仍然存在,则必须在OnPaint期间绘制它.

If you want it to still be there after something happens to your form, such as minimize, you have to draw it during OnPaint.

这是我的建议:

public partial class Form1 : Form
{
    Rectangle r = Rectangle.Empty;
    Pen redPen = new Pen(Color.Red);

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        r = new Rectangle(50, 50, 100, 100);
        Refresh();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        if (r != Rectangle.Empty)
        {
            e.Graphics.DrawRectangle(redPen, r);
        }
    }
}

这篇关于C#画线OnPaint()与CreateGraphics()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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