【问题标题】:Why after drawing circles their colors change?为什么画完圆圈后颜色会变?
【发布时间】:2016-07-12 22:49:36
【问题描述】:

为什么画完圆圈后颜色会变? ,其实我画的是圆圈,但我的问题是每次双击后,下一个圆圈的颜色都会从蓝色变为背景色。

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();
        }
    }

【问题讨论】:

  • using 语句中在循环外创建笔。例如using (var pen = new Pen(Color.Tomato, 2){ /* Rest of Code*/ }using 语句以正确的方式调用对象上的Dispose 方法,并且(当您如前所示使用它时)它还会导致对象本身在调用Dispose 时立即超出范围。在using 块内,对象是只读的,不能修改或重新分配。

标签: c# winforms picturebox


【解决方案1】:

您正确地绘制了椭圆,但您始终只填充其中一个(添加的最后一个,在光标的位置)。

// 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);

【讨论】:

    【解决方案2】:

    改变 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();
                }
    
            }
    

    【讨论】:

    • 为什么要为每个点创建一支新笔?为什么不使用同一支笔。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 2015-11-28
    • 2016-10-10
    • 1970-01-01
    • 2012-08-01
    • 2011-09-25
    相关资源
    最近更新 更多