开发者

selected area to cut an image

Hi I would do the selected area to cut an 开发者_如何学Pythonimage on picturebox control.

I have the following code:

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

namespace WindowsFormsApplication1
{

public partial class Form1 : Form
{
    private Rectangle rect;
    private Pen p;

    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        if (this.p == null)
            this.p = new Pen(Color.FromArgb(100, 200, 200, 200), 5);
        if (this.rect.Width > 0)
            e.Graphics.DrawRectangle(this.p, this.rect);
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {

        if (e.X < this.rect.X)
        {
            this.rect.Width = this.rect.X - e.X;
            this.rect.X = e.X;
        }
        else
        {
            this.rect.Width = e.X - this.rect.X;
        }

        if (e.Y < this.rect.Y)
        {
            this.rect.Height = this.rect.Y - e.Y;
            this.rect.Y = e.Y;
        }
        else
        {
            this.rect.Height = e.Y - this.rect.Y;
        }

        this.Invalidate(this.rect);

    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        this.rect.X = e.X;
        this.rect.Y = e.Y;
    }

}

}

It returns an error here:

Application.Run(new Form1());

Why?

thanks for all replies ;p


You shouldn't dispose of the Graphics object that is passed as part of the PaintEventArgs. That is probably what is causing your issue.


Try using this optimized code, if you still get error post it here (edit your original question) and we'll see.

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
   if (this.p == nulll)
      this.p = new Pen(Color.FromArgb(100, 200, 200, 200), 5);
   if (this.rect.Width > 0)
      e.Graphics.DrawRectangle(this.p, this.rect);
}


what is the error?

you are leaking Pen's. For every paint message you create a new pen and throw the old without disposing.

Off the top of my head I can't remember if you should dispose of the graphics object you get from the event args

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜