2017-10-04 71 views
0

在我的表格中,我有一個圖片框。我希望能夠在圖像上繪製箭頭。我設法在一半。在表單加載事件中,我將一個圖像分配給圖片框。我可以用下面的代碼創建箭頭。問題是每次創建箭頭時,我在表單加載事件上分配的圖片都會被擦除。爲什麼我的圖像被擦除?如何在繪製箭頭的同時保持我在圖像加載時分配的圖像?在畫上時保留圖片盒的圖像

private bool isMoving = false; 
    private Point mouseDownPosition = Point.Empty; 
    private Point mouseMovePosition = Point.Empty; 
    private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>(); 
    Pen _Pen; 

    private void Test_Load(object sender, EventArgs e) 
    { 
     pictureBox1.Image = Properties.Resources.background;   
    } 

    private void pictureBox1_Paint(object sender, PaintEventArgs e) 
    { 

     if (isMoving) 
     { 
      if (pictureBox1.Image == null) 
      { 
       Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height); 
       using (Graphics g = Graphics.FromImage(bmp)) 
       { 
        g.Clear(Color.White); 
       } 
       pictureBox1.Image = bmp; 
      } 

      using (Graphics g = Graphics.FromImage(pictureBox1.Image)) 
      { 
       g.Clear(pictureBox1.BackColor); 

       AdjustableArrowCap bigArrow = new AdjustableArrowCap(5, 5); 
       _Pen = new Pen(Color.IndianRed, 3); 
       _Pen.CustomEndCap = bigArrow; 
       g.DrawLine(_Pen, mouseDownPosition, mouseMovePosition); 
       _Pen.Dispose(); 
      } 
     } 
    } 



    private void pictureBox1_MouseDown(object sender, MouseEventArgs e) 
    { 
     isMoving = true; 
     mouseDownPosition = e.Location; 
    } 

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e) 
    { 
     if (isMoving) 
     { 
      mouseMovePosition = e.Location; 
      pictureBox1.Invalidate(); 
     } 
    } 

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e) 
    { 
     if (isMoving) 
     { 
      lines.Add(Tuple.Create(mouseDownPosition, mouseMovePosition)); 
     } 
     isMoving = false; 
    } 

我認爲這個問題是與這條線在這裏g.Clear(pictureBox1.BackColor);

回答

1

是的,問題是這條線在這裏g.Clear(pictureBox1.BackColor);你你劃清界線前擦除整個控制區。

你應該畫到e.Graphics直接:

private void pictureBox1_Paint(object sender, PaintEventArgs e) 
{ 
    if (isMoving) 
    { 
     if (pictureBox1.Image == null) e.Graphics.Clear(Color.White); 

     // Add this line for high quality drawing: 
     e.Graphics.SmoothingMode = SmoothingMode.HighQuality; 

     AdjustableArrowCap bigArrow = new AdjustableArrowCap(5, 5); 
     _Pen = new Pen(Color.IndianRed, 3); 
     _Pen.CustomEndCap = bigArrow; 
     e.Graphics.DrawLine(_Pen, mouseDownPosition, mouseMovePosition); 
     _Pen.Dispose(); 
    } 
} 
+0

嗨櫻,這個工作。謝謝!這將保留背景圖像並在其上繪製箭頭,但是您知道爲什麼圖像箱圖像不等於背景圖片上方的繪製箭頭嗎?我測試這個的方式是我把另一個picturebox控件放在我的表單中,只寫了'picturebox2.image = picturebox1.image',它只顯示我的背景圖片。 – taji01

+0

將if(pictureBox1.Image == null)'更改爲'if((sender as PictureBox).Image == null)'。無論如何,我不清楚你的評論。如果可能的話,用新代碼編輯你的問題,我會看看我是否可以幫助 – Sakura

+0

嗨櫻,我在這裏更詳細地詢問了我跑過的測試的問題。 https://stackoverflow.com/questions/46592322/paint-drawline-image-into-picturebox-image – taji01