close
C# 視窗程式範例--小畫板
專案下載:Painter.zip
程式範例
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace Painter
{
public partial class Form1 : Form
{
Graphics g; // 繪圖區
Pen pen; // 畫筆
bool isMouseDown = false; // 紀錄滑鼠是否被按下
List<Point> points = new List<Point>(); // 紀錄滑鼠軌跡的陣列。
public Form1()
{
InitializeComponent();
g = this.CreateGraphics(); // 取得繪圖區物件
pen = new Pen(Color.Black, 3); // 設定畫筆為黑色、粗細為 3 點。
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
isMouseDown = true; // 滑鼠被按下後設定旗標值。
points.Add(e.Location); // 將點加入到 points 陣列當中。
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown) // 如果滑鼠被按下
{
points.Add(e.Location); // 將點加入到 points 陣列當中。
// 畫出上一點到此點的線段。
g.DrawLine(pen, points[points.Count - 2], points[points.Count - 1]);
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
points.Add(new Point(-1, -1)); // 滑鼠放開時,插入一個斷點 (-1,-1),以代表前後兩點之間有斷開。
isMouseDown = false; // 滑鼠已經沒有被按下了。
}
}
}
執行結果

圖一、小畫板的執行結果
範例改良版 (resize 不會消失)
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Graphics g; // 繪圖區
Pen pen; // 畫筆
bool isMouseDown = false; // 紀錄滑鼠是否被按下
List<Point> points = new List<Point>(); // 紀錄滑鼠軌跡的陣列。
public Form1()
{
InitializeComponent();
g = this.CreateGraphics();
pen = new Pen(Color.Black, 5);
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
isMouseDown = true;
points.Add(e.Location);
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
points.Add(new Point(-1, -1));
isMouseDown = false;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown)
{
points.Add(e.Location);
// g.DrawLine(pen, points[points.Count - 2], points[points.Count - 1]);
this.Invalidate();
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
for (int i = 0; i < points.Count-1; i++)
{
if (points[i].X >=0 && points[i+1].X >=0)
g.DrawLine(pen, points[i], points[i+1]);
}
}
}
}
文章來源:陳鍾誠 (2010年10月05日),(網頁標題) 小畫板 — 用 C# 實作,(網站標題) 免費電子書:C# 程式設計,2010年10月05日,取自 http://cs0.wikidot.com/painter ,網頁修改第 17 版。
文章標籤
全站熱搜