橡皮筋技術問題描述:
畫線時:
在我放開鼠標左鍵確定之前會有一條虛線顯示將來要 "畫 "的那條線的情況.此時隨着鼠標自由移動,虛線也跟着變長變短.就好像在拉橡皮筋.
當放開左鍵後.虛線消失,然後畫出線.
請問:如何實現這條虛線?
如何實現虛線的不斷刷新,重畫?
並且要保證當我停止移動鼠標時,那條虛線是存在的.
解決方案:
在用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));
}