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

时间:2016-02-10 00:19:02

标签: c# .net winforms paint picturebox

我正在使用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;
        }

   }

enter image description here

1 个答案:

答案 0 :(得分:1)

最好使用GraphicsPath

enter image description here

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了解差异!
  • 您可以添加更多矩形或其他形状以排除。

如果您想要合并图像和曲面,请绘制图像或向PictureBox DrawToBitmap询问..