GDI+ C# 在图片上画矩形

来源:互联网 发布:西安少儿编程培训班 编辑:程序博客网 时间:2024/04/30 01:17

//定义全局变量 
  private int pointStartX, pointStartY, pointEndX, pointEndY  
  private Bitmap bitmapSource = null;
 //初始化中          
     string strPath = "C:\\Users\\Public\\Pictures\\Sample Pictures\\22.jpg";
            bitmapSource = new Bitmap(strPath);
 //在MouseDown事件中记下起始点          
     pointStartX = e.X;
            pointStartY = e.Y;
 //C#中利用GDI+ ,在MouseMove事件中绘制矩形   
     int iWidth = e.X - pointStartX;
            int iHeight = e.Y - pointStartY;
            if (e.Button == MouseButtons.Left)
            {
                // 每次鼠标移动都拷贝原图bitmapSource,去除之前的留下的矩形
                Bitmap bitmap = new Bitmap(bitmapSource, 500, 500);
                Pen pen = new Pen(Color.Red);
                Graphics gh = Graphics.FromImage(bitmap);
                Rectangle rectNew = new Rectangle(pointStartX, pointStartY, iWidth, iHeight);
                // 画矩形
                gh.DrawRectangle(pen, rectNew);
                // 显示在画板上
                this.CreateGraphics().DrawImage(bitmap, 0, 0, 500, 500);
            }

原创粉丝点击