Skip to main content
 首页 » 编程设计

c#之选定区域以剪切图像

2024年02月23日12落叶无声

您好,我会选择区域来剪切 picturebox 控件上的图像。

我有以下代码:

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

这里返回错误:

Application.Run(new Form1()); 

为什么?

谢谢大家的回复;p

请您参考如下方法:

您不应处置作为 PaintEventArgs 的一部分传递的 Graphics 对象。这可能是导致您出现问题的原因。