在图片框 C# 内绘制某些区域

Paint Certain Areas inside of a Picture Box C#

我正在使用 WinForms。在我的表单中,我有一个带有图像的图片框。我如何绘制图片框而不是扩展正方形内的区域。这是我的代码。目前我可以创建扩展的正方形,但我不知道如何在该正方形外将图片框涂成白色。

    int _cropX, _cropY, _cropWidth, _cropHeight;
    private State _currentState;

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (Crop_Checkbox.Checked == true)
        {
            if (_currentState == State.Crop)
            {
                Cursor = Cursors.Cross;
                if (e.Button == System.Windows.Forms.MouseButtons.Left)
                {
                    //X and Y are the coordinates of Crop
                    pictureBox1.Refresh();
                    _cropWidth = e.X - _cropX;
                    _cropHeight = e.Y - _cropY;
                    pictureBox1.CreateGraphics().DrawRectangle(_cropPen, _cropX, _cropY, _cropWidth, _cropHeight);
                }

            }
        }
        else
        {
            Cursor = Cursors.Default;
        }
    }

    private void Crop_Checkbox_CheckedChanged(object sender, EventArgs e)
    {
        if (Crop_Checkbox.Checked == true)
        {
            this.Cursor = Cursors.Cross;
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (Crop_Checkbox.Checked == true)
        {
            if (_currentState == State.Crop)
            {
                if (e.Button == System.Windows.Forms.MouseButtons.Left)
                {
                    Cursor = Cursors.Cross;
                    _cropX = e.X;
                    _cropY = e.Y;

                    _cropPen = new Pen(Color.FromArgb(153, 180, 209), 3); //2 is Thickness of line

                    _cropPen.DashStyle = DashStyle.DashDotDot;
                    pictureBox1.Refresh();
                }
            }
        }
        else
        {
            Cursor = Cursors.Default;
        }
    }

    public Pen _cropPen;

    private enum State
    {
        Crop
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {

        if (Crop_Checkbox.Checked == true)
        {
          //Paint picturebox...

        }
        else
        {
            Cursor = Cursors.Default;
        }

   }

最好使用 GraphicsPath:

using System.Drawing.Drawing2D;
..

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    Rectangle r1 = pictureBox1.ClientRectangle;  // note I don't use width or height!
    Rectangle r2 = new Rectangle(50, 30, 80, 40);
    GraphicsPath gp = new GraphicsPath(FillMode.Alternate);
    gp.AddRectangle(r1);  // first the big one
    gp.AddRectangle(r2);  // now the one to exclude
    e.Graphics.FillPath( Brushes.Gold, gp);
}

注意我..

  • ..将 Paint 事件用于持久图形
  • ..仅在 PictureBox 表面 上绘制,而不是在其 图像 上绘制。区别见here
  • 您可以添加更多要排除的矩形或其他形状。

如果你想要图像和表面结合,要么绘制到图像中,要么询问 PictureBoxDrawToBitmap..