橡皮筋技术问题描述:
画线时:
在我放开鼠标左键确定之前会有一条虚线显示将来要 "画 "的那条线的情况.此时随着鼠标自由移动,虚线也跟着变长变短.就好像在拉橡皮筋.
当放开左键后.虚线消失,然后画出线.
请问:如何实现这条虚线?
如何实现虚线的不断刷新,重画?
并且要保证当我停止移动鼠标时,那条虚线是存在的.
解决方案:
在用C#结合GDI+技术实现画图板的时候,涉及到绘制线,面时候的橡皮筋(橡皮条)技术。这里是通过以下方法解决:(以绘制直线为例)
(先假设以下条件,您要使用PictureBox控件来显示绘图结果)
1:变量声明:
/// <summary>
/// 画笔
/// </summary>
Pen myPen;
/// <summary>
/// 画刷
/// </summary>
Brush myBrush;
/// <summary>
/// 画笔颜色
/// </summary>
Color myColorOfPen;
/// <summary>
/// 画笔宽度,默认为1
/// </summary>
int vPenWidth=1;
/// <summary>
/// 当前绘画方式
/// </summary>
string strDrawMode;
/// <summary>
/// 画布的宽度
/// </summary>
int vPicBoxWidth;
/// <summary>
/// 画布的高度
/// </summary>
int vPicBoxHeight;
/// <summary>
/// 全局的Bitmap
/// </summary>
Bitmap myOriginalBitmap;
/// <summary>
/// 临时显示图像的bitmap
/// </summary>
Bitmap myShowBitmap;
/// <summary>
/// 起点
/// </summary>
Point myStartPoint;
/// <summary>
/// 判断是否开始绘图
/// </summary>
bool isStart = false;
/// <summary>
/// Graphics
/// </summary>
Graphics gShow;
2:核心代码:
public FormMain()
{
InitializeComponent();
vPicBoxWidth = this.MypictureBox.Width;
vPicBoxHeight = this.MypictureBox.Height;
myOriginalBitmap = new Bitmap(vPicBoxWidth, vPicBoxHeight);
gShow = this.MypictureBox.CreateGraphics();
}
private void MypictureBox_MouseDown(object sender, MouseEventArgs e)
{
if (MycomboBoxOfDrawMode .Text ==null) //这里是通过一个comboBox控件来设置当前绘制的内容(如点、线、面)
{
return;
}
if (e.Button==MouseButtons.Left )
{
isStart = true;
strDrawMode = MycomboBoxOfDrawMode.Text.ToString();
myPen = new Pen(myColorOfPen, vPenWidth);
Graphics gOriginal = Graphics.FromImage(myOriginalBitmap);
switch (strDrawMode)
{
case "Point":
//TODO:
break;
case "Line":
myStartPoint = new Point(e.X, e.Y);
break;
case "Rectangle":
break;
case "Ellipse":
break;
case "Paint":
break;
default:
break;
}
}
else if (e.Button==MouseButtons.Right )
{
isStart = false;
}
}
private void MypictureBox_MouseMove(object sender, MouseEventArgs e)
{
MytoolStripStatusLabel.Text = " 当前坐标为:X=" + e.X.ToString()
+ ",Y=" + e.Y.ToString();
if (isStart==true )
{
myShowBitmap = (Bitmap)myOriginalBitmap.Clone();//每次鼠标移动的时候都复制原始图片作为底图
//在该图层上绘制
//即可实现橡皮条功能
Graphics g = Graphics.FromImage(myShowBitmap);
switch (strDrawMode)
{
case "Line":
g.DrawLine(myPen, myStartPoint, new Point(e.X, e.Y));//在myShowBitmap上绘制图像
g.Dispose();
MypictureBox.BackgroundImage = myShowBitmap;
break;
default:
break;
}
}
}
private void MypictureBox_MouseUp(object sender, MouseEventArgs e)
{
if (strDrawMode =="Line")
{
myOriginalBitmap = (Bitmap)myShowBitmap.Clone();//把ShowBitmap图层内容拷贝到原始图层中
gShow.DrawImage(myOriginalBitmap, new Point(0, 0));
}
if (strDrawMode =="Point")
{
gShow.DrawImage(myOriginalBitmap, new Point(0, 0));
}
}
/// <summary>
/// 重写重绘事件
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Bitmap aBitmap = (Bitmap)myOriginalBitmap.Clone();
gShow.DrawImage(aBitmap, new Point(0, 0));
}