c#矩形框的绘制

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44913038/article/details/102567489
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 画笔
{
    public partial class Form1 : Form
    {
        bool draw;//判断是否要开始画矩形框
        Point start; //画框的起始点
        Point end;//画框的结束点
        Point last_start, last_end;//用于记录上一个矩形框的位置
        int i = 0;
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            Graphics g = this.pictureBox1.CreateGraphics();
            Pen mypen = new Pen(Color.Red, 3);//设置画笔属性
            g.DrawRectangle(mypen,10,100,50,50);//按按钮画一个矩形
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
           
            Graphics g = this.pictureBox1.CreateGraphics();
           ////////擦除上一个矩形框,防止鼠标拖动过程中,绘制多个矩形////// 
            if (e.Button == MouseButtons.Left)//如果鼠标左键按下就执行
            {
                Pen newpen = new Pen(Color.White, 3);
                i++;
                if(i>1)
                g.DrawRectangle(newpen, last_start.X, last_start.Y, last_end.X - last_start.X, last_end.Y - last_start.Y);//擦除之前的矩形
            }
          ////////擦除上一个矩形框,防止鼠标拖动过程中,绘制多个矩形////// 

         /////////////////////绘制矩形//////////////////////  
            Pen mypen = new Pen(Color.Red, 3);
            if (draw)
            {
                Point nowpoint = this.PointToClient(Control.MousePosition);
                int Width1 = nowpoint.X - start.X;
                int Height1 = nowpoint.Y - start.Y;
                g.DrawRectangle(mypen,start.X,start.Y,Width1,Height1);
            }
            /////////////////////绘制矩形////////////////////// 
            
            end = this.PointToClient(Control.MousePosition);
            last_start = start;//记录当前矩形位置起始坐标
            last_end = end;//记录当前矩形位置终点坐标

        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            i = 0;
            start = this.PointToClient(Control.MousePosition);//获取鼠标位置
            draw = true;
        }


        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            draw = false;
        }
    }
}

效果如下
在这里插入图片描述
将picturebox控件背景设置成白色

猜你喜欢

转载自blog.csdn.net/weixin_44913038/article/details/102567489