C# picturebox画矩形、圆

发布时间 2023-08-09 11:06:18作者: JIAXUN

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 自定义画矩形
{
/// <summary>
/// 类型:1、画矩形 2、画圆
/// 绘制按钮:drawState = true;
/// 移动按钮:moveState = true;
/// 4个事件:MouseDown、MouseUp、MouseMove、Pain
/// 窗体LOAD事件加入以下代码:
/// </summary>

// this.SetStyle(ControlStyles.ResizeRedraw, true);
// this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
// this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
// this.SetStyle(ControlStyles.UserPaint, true);
// this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
// this.UpdateStyles();
public class DrawRect
{
Pen pen;
Rectangle rectangle;
//左键是否按下
public bool leftClick = false;
//绘制状态
public bool drawState = false;
//移动模式
public bool moveState = false;
//移动模式下位移前的点坐标
public Point point = new Point();

PictureBox pictureBox1;
//框类型
int type;

public DrawRect(PictureBox pictureBox,int _type)
{
pictureBox1 = pictureBox;
pen = new Pen(Color.FromArgb(0, 192, 0), 1);
rectangle = new Rectangle();
type = _type;
}

public void MouseDown(object sender, MouseEventArgs e)
{
//判断是否处于绘制状态
if (drawState)
{
rectangle.X = e.X;
rectangle.Y = e.Y;
//左键被按下
leftClick = true;
}
else if (moveState)
{
//左键被按下
leftClick = true;
//记录当前坐标值
point.X = e.X;
point.Y = e.Y;
}
}

public void MouseUp(object sender, MouseEventArgs e)
{
if (drawState)
{
//完成绘制
leftClick = false;
drawState = false;
pictureBox1.Invalidate();
}
else if (moveState)
{
//完成移动
leftClick = false;
moveState = false;
pictureBox1.Invalidate();
}
}

public void MouseMove(object sender, MouseEventArgs e)
{
if (drawState)
{
//判断左键是否按下
if (leftClick)
{
rectangle.Width = e.X - rectangle.X;
rectangle.Height = e.Y - rectangle.Y;
pictureBox1.Invalidate();
}
}
else if (moveState)
{
//判断左键是否按下
if (leftClick)
{
rectangle.X = rectangle.X + (e.X - point.X);
rectangle.Y = rectangle.Y + (e.Y - point.Y);
pictureBox1.Invalidate();
//位移前的点坐标
point.X = e.X;
point.Y = e.Y;
}
}
}

public void Pain(object sender, PaintEventArgs e)
{
if (type == 1)
{
e.Graphics.DrawRectangle(pen, rectangle);
} else if (type == 2)
{
e.Graphics.DrawEllipse(pen, rectangle);
}
}
}
}