---
# System prepended metadata

title: 54第一題

---

<h2>
    小畫家
</h2>

<h3>程式要求:</h3>

1.使用功能表切換畫筆顏色
2.按下滑鼠開始畫線，放開停止畫線，可拖拉滑鼠繪製圖形
3.會比線條顏色是目前選擇的畫筆色彩
<h3>
    介面設計
</h3>

使用PictureBox當作畫布
在頂部再放一個menustrip 來切換畫筆顏色![image](https://hackmd.io/_uploads/HJ2Uf0Qsa.png)

<h3>
    我的作法:
</h3>

先設定畫筆的初始位置
```csharp
public Point start;
```
在讓畫筆的初始顏色定義為藍色
```csharp
private Pen pen = new Pen(Color.Blue, 2);
```
最後再把起始點設定好
```csharp
private Point start;
```
設置三個事件，分別為:MouseDown，MouseMove和MouseUp
我們要讓滑鼠左鍵按下後再移動滑鼠繪製線條
先設一個變數
```csharp
private bool drawing = false;
```
要讓他預設為false
然後在滑鼠按下的時候設為true
跟設定start的起始位置
```csharp
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    drawing = true;
    start = e.Location;
}
```
如果MouseMove事件偵測到drawing == true
就在pictureBox上面建立一個Graphics 物件
並且使用 pictureBox1.CreateGraphics() 方法
讓他可以在pictureBox上畫畫
```csharp
 private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
 {
     if (drawing)
     {
         using (Graphics g = pictureBox1.CreateGraphics())
         {
             g.DrawLine(pen, start, e.Location);
             start = e.Location;
         }
     }
 }
```
如果滑鼠按鍵放開drawing == false
```csharp
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    drawing = false;
}
```
完整程式碼
```csharp=
public partial class Form1 : Form
{
    private Pen pen;
    private Point start;
    private bool drawing = false;
    public Form1()
    {
        InitializeComponent();
        InitializePoint();
    }
    private void InitializePoint()
    {
        pen = new Pen(Color.Blue, 2);
    }
    private void 紅色ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        紅色ToolStripMenuItem.Checked = true;
        藍色ToolStripMenuItem.Checked = false;
        綠色ToolStripMenuItem.Checked = false;
        pen = new Pen(Color.Red, 2);
    }

    private void 藍色ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        紅色ToolStripMenuItem.Checked = false;
        藍色ToolStripMenuItem.Checked = true;
        綠色ToolStripMenuItem.Checked = false;
        pen = new Pen(Color.Blue, 2);
    }

    private void 綠色ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        紅色ToolStripMenuItem.Checked = false;
        藍色ToolStripMenuItem.Checked = false;
        綠色ToolStripMenuItem.Checked = true;
        pen = new Pen(Color.Green, 2);
    }
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        drawing = true;
        start = e.Location;
    }
    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (drawing)
        {
            using (Graphics g = pictureBox1.CreateGraphics())
            {
                g.DrawLine(pen, start, e.Location);
                start = e.Location;
            }
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        drawing = false;
    }
}
```




     


    


