开发者

Deleting GDI+ objects

I am building a C# application that uses GDI+ to draw images and shapes to the form but I have no idea how to delete them. Let's say I have a optional grid drawn using GDI+ and when users turns it off, I want to, well, turn it off, delete it somehow and without affecting other objects on the working canvas. What is the best approach? Than开发者_运维问答ks!


A simple example, drop a CheckBox on the form:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        checkBox1.CheckedChanged += new EventHandler(checkBox1_CheckedChanged);
    }
    private void checkBox1_CheckedChanged(object sender, EventArgs e) {
        this.Invalidate();
    }
    protected override void OnPaint(PaintEventArgs e) {
        if (checkBox1.Checked) {
            e.Graphics.DrawArc(Pens.Black, this.ClientRectangle, 0, 360);
        }
    }
}

Calling Invalidate() is the key to erasing the original drawing, it forces the form to be repainted. The default OnPaintBackground method implemented by the base class turns everything back to battleship gray.


Windows does not store your bitmap output. To remove an item, use a flag to draw it conditionally in OnPaint(). Set the flag to false and call Invalidate() on the Control in question.


In addition that other users said, I'd recommend for performance using Invalidate(region) only in the necessary region, not for all the drawing area.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜