2016-07-12 42 views
4

爲什麼在繪製圓圈後顏色發生變化?實際上,我畫了圓圈,但是我的問題是,每次雙擊後,下一個圓圈的顏色會從藍色變爲背景顏色。爲什麼畫圓後他們的顏色會改變?

public Form1() 
    { 
     InitializeComponent(); 
     pictureBox1.Paint += new PaintEventHandler(pic_Paint); 
    } 

    public Point positionCursor { get; set; } 
    private List<Point> points = new List<Point>(); 
    public int circleNumber { get; set; } 

    private void pictureBox1_DoubleClick(object sender, EventArgs e) 
    { 
     positionCursor = this.PointToClient(new Point(Cursor.Position.X - 25, Cursor.Position.Y - 25)); 

     points.Add(positionCursor); 

     pictureBox1.Invalidate(); 
    } 

    private void pic_Paint(object sender, PaintEventArgs e) 
    { 
     Graphics g = e.Graphics; 
     g.SmoothingMode = SmoothingMode.AntiAlias; 

     foreach (Point pt in points) 
     { 
      Pen p = new Pen(Color.Tomato, 2); 

      g.FillEllipse(Brushes.Blue, positionCursor.X, positionCursor.Y, 20, 20); 

      g.DrawEllipse(p, pt.X, pt.Y, 20, 20); 

      p.Dispose(); 
     } 
    } 

enter image description here

+1

創建循環外的筆,在[使用](https://msdn.microsoft.com/en-us//library/yh598w02.aspx )聲明。例如'using(var pen = new Pen(Color.Tomato,2){/ * Rest of Code * /}'。'using'語句以正確的方式調用對象上的Dispose方法,如前所述,它也會導致對象本身在調用Dispose後立即超出範圍,在'using'塊中,對象是隻讀的,不能被修改或重新分配。 –

回答

3

你正確繪製橢圓,但你總是隻填寫其中的一個(最後一個加入,在光標的位置)。

// This is ok 
g.DrawEllipse(p, pt.X, pt.Y, 20, 20); 

// You should use pt.X and pt.Y here 
g.FillEllipse(Brushes.Blue, positionCursor.X, positionCursor.Y, 20, 20); 
0

變化pic_Paint如下

private void pic_Paint(object sender, PaintEventArgs e) 
     { 
      Graphics g = e.Graphics; 
      g.SmoothingMode = SmoothingMode.AntiAlias; 

      foreach (Point pt in points) 
      { 
       Pen p = new Pen(Color.Tomato, 2); 
       g.DrawEllipse(p, pt.X, pt.Y, 20, 20); 
       g.FillEllipse(Brushes.Blue, pt.X, pt.Y, 20, 20); 
       p.Dispose(); 
      } 

     } 
+0

爲什麼創建每個點的新筆?爲什麼不使用同一支筆。 – ja72

相關問題