PictureBox中拖动鼠标画曲线;

来源:互联网 发布:php比较文件内容 编辑:程序博客网 时间:2024/05/21 22:21

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

//picturebox放在panel上,然后picturebox的sizemode设置成autosize,panel的autoscroll设置成true;

namespace PictureBox_DrawLine
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Bitmap bits=new Bitmap (10,10);
        private bool mark = false;
        private Point point1;

        //图形框显示图像被破坏需恢复时,图形框自动响应Paint事件,用属性Image引用位图圣像恢复
        //所绘制的图形;因此绘制图形必须记录到图形框属性Image引用的位图对象中才能被保存;
        private Graphics bitG;

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //撤消bisG引用的对象;
            bits.Dispose();            

            OpenFileDialog openfiledialog = new OpenFileDialog();
            openfiledialog.Filter = "*.jpg|*.jpg|*.bmp|*.bmp";
            openfiledialog.ShowDialog();
            Image image = Image.FromFile(openfiledialog.FileName);
            bits = new Bitmap (  image);

            bitG = Graphics.FromImage(bits);
            image.Dispose();
            pictureBox1.Image = bits;
          
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            mark = true;
            point1 = new Point(e.X, e.Y);
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (mark)
            {
                Point point2 = new Point(e.X, e.Y);
                Pen pen = new Pen(Color.Black, 2);
                Graphics g = pictureBox1.CreateGraphics();
                g.DrawLine(pen, point1, point2);  //图形画在picturebox1表面

                bitG.DrawLine(pen, point1, point2);//图形画在位图对象bist中;
                point1.X = e.X;
                point1.Y = e.Y;
            }
        }

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

       
    }
}
 

原创粉丝点击