winform 根据鼠标移动画线

绘制如图:

 

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        //MyPoint1, MyPoint2表示鼠标按下和弹起时鼠标的坐标位置
        public Point MyPoint1, MyPoint2;
        //是否绘制
        public int MyFlag = 0;
        //GDI+
        Graphics g = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = "当前坐标点:X=" + 0.ToString() + ",Y=" + 0.ToString();
            g = this.CreateGraphics();
            this.BackColor = Color.WhiteSmoke;
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            //当鼠标弹起时,设置MyFlag = 0,表示不能画线
            this.MyFlag = 0;
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            this.Text = "当前坐标点:X=" + e.X.ToString() + ",Y=" + e.Y.ToString();

            //使绘图质量最高,即消除锯齿
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.InterpolationMode = InterpolationMode.High;
            g.CompositingQuality = CompositingQuality.HighQuality;
            Pen MyPen = new Pen(Color.Black, 3.0F);

            //MyFlag=0表示鼠标弹起,不能进行画线
            //当鼠标按下时,设置MyFlag=1表示可以画线
            if (this.MyFlag == 0)
                return;

            //鼠标移动,每次变换时,MyPoint2都记录下鼠标的位置,以便进行鼠标移动画线
            this.MyPoint2.X = e.X;
            this.MyPoint2.Y = e.Y;
            g.DrawLine(MyPen, MyPoint1, MyPoint2);

            //当画完一条线后(很短的,可以当做一个小点看待),将MyPoint1的坐标重置为此时鼠标的位置
            MyPoint1.X = e.X;
            MyPoint1.Y = e.Y;
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            //鼠标第一次按下时,设置鼠标坐标为第一个点的坐标
            this.MyFlag = 1;
            this.MyPoint1.X = e.X;
            this.MyPoint1.Y = e.Y;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            g.Clear(Color.WhiteSmoke);
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            g = this.CreateGraphics();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            g.Clear(Color.WhiteSmoke);
        }

    }
}

参考原文:https://blog.csdn.net/hui_shixu/article/details/7738410

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangnaisheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值