C#用鼠标绘图笔记(一)

       这是本人第一次在blog上发一个小代码,水平有限,慢慢努力
       这是用C#编写的关于用鼠标绘图代码,代码及讲解如下


using  System;
using  System.Drawing;
using  System.Collections;
using  System.ComponentModel;
using  System.Windows.Forms;

namespace  Test
{
    
public class Form3 : System.Windows.Forms.Form
    
{
        
private System.ComponentModel.Container components = null;
        
private System.Windows.Forms.PictureBox pictureBox1;
        
private System.Drawing.Point startPoint;
        
private System.Drawing.Bitmap bitmap;
        
private bool CanMove=false;

        
public Form3()
        
{
            InitializeComponent();
                //创建缓冲
            
this.SetStyle(ControlStyles.UserPaint, true);
            
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);    
            
this.SetStyle(ControlStyles.DoubleBuffer, true);
            bitmap 
= new Bitmap(this.pictureBox1.Width,this.pictureBox1.Height);
            
this.pictureBox1.Image=bitmap;
        }

        
protected override void Dispose( bool disposing )
        
{
            
if( disposing )
            
{
                
if(components != null)
                
{
                    components.Dispose();
                }

            }

            
base.Dispose( disposing );
        }


        
Windows 窗体设计器生成的代码

        
private void pictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        
{
            
this.CanMove=true;
            
this.startPoint=new Point(e.X,e.Y);
        }


        
private void pictureBox1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        
{
            
if(this.CanMove==true)
            
{
                
this.pictureBox1.Image=(Bitmap)this.bitmap.Clone();
                
using(Graphics graphics = Graphics.FromImage(this.pictureBox1.Image))
                      
{
                    graphics.Clear(Color.Transparent);
//清除
                    graphics.DrawLine(new Pen(Color.Red,1),this.startPoint,new Point(e.X,e.Y));//重绘
                    graphics.DrawImage(this.bitmap,this.pictureBox1.Location.X,this.pictureBox1.Location.Y,this.pictureBox1.Width,this.pictureBox1.Height);
                }

            }
        
        }


        
private void pictureBox1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        
{
            
this.pictureBox1.Image = this.bitmap;
            
using(Graphics graphics = Graphics.FromImage(this.pictureBox1.Image))
                  
{
                graphics.DrawLine(
new Pen(Color.Red,1),this.startPoint,new Point(e.X,e.Y));
            }

            
this.CanMove=false;
        }

    }

}


参考:
http://www.codeproject.com/dotnet/rubberbandline.asp
 

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值