仅为某些画笔刷新画布

时间:2015-08-14 09:43:44

标签: c# graphics drawing

我正在尝试绘制一些圆圈和线条等,但我只想在画布上刷新一些线条而其他线条不要,有什么方法可以解决这个问题吗?

例如mypen,mypen2和mypen3,我希望它们在画布上刷新,但图形“g”稍微向下我不想刷新,我想要显示所有实例。我该怎么做呢?这是我的代码

private void drawlines()
{
    canvas.Refresh();
    int j = Int32.Parse(ivalue.Text);

    float position1 = canvas.Width / 2;
    float position2 = canvas.Height / 2;

    float XX = (float)(Math.Round(position1 + Math.Sin(DegreeToRadian(j)) * 100));
    float XY = (float)(Math.Round(position2 - Math.Cos(DegreeToRadian(j)) * 100));
    float X2 = (position1 + XX);

    float XY2 = XY;

    System.Drawing.Pen myPen;
    System.Drawing.Pen myPen2;
    System.Drawing.Pen myPen3;
    System.Drawing.Pen myPen4;

    myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
    myPen2 = new System.Drawing.Pen(System.Drawing.Color.Blue);
    myPen3 = new System.Drawing.Pen(System.Drawing.Color.Black);
    myPen4 = new System.Drawing.Pen(System.Drawing.Color.Green);
    System.Drawing.Graphics formGraphics = canvas.CreateGraphics();
    formGraphics.DrawRectangle(myPen,XX, XY,3,3);
    formGraphics.DrawRectangle(myPen2, canvas.Width / 2, XY, 3, 3);
    formGraphics.DrawRectangle(myPen3, position1, position2, 3, 3);
    formGraphics.DrawRectangle(myPen4, position1, XY2, 3, 3);
    label1.Text = Convert.ToString(XY);
    label1.Refresh();

    listBox1.Items.Clear();

    listBox1.Items.Add("XX=[" + XX + "] XY=[" + XY + "]");
} 


private void Go_Click(object sender, EventArgs e)
{
    for (int i = 0; i <= 360; i = i + 1)
    {
        drawlines();
        int linearm = (canvas.Width / 2) - i;

        ivalue.Text = Convert.ToString(i);
        ivalue.Refresh();
        int testx = Int32.Parse(label1.Text);

        Graphics g;
        g = canvas.CreateGraphics();
        Pen p;
        Rectangle r;
        p = new Pen(Brushes.Green);
        r = new Rectangle(linearm,testx, 1, 1);

        g.DrawRectangle(p, r);

        System.Threading.Thread.Sleep(15);
    }
}

1 个答案:

答案 0 :(得分:1)

我假设您正在使用winforms?如果是这样,您需要将代码更改为以下方式:

为了保持持久性,需要在Paint事件中绘制并使用其e.Graphics对象。 (这是黄金法则!推论:永远不要使用System.Drawing.Graphics formGraphics = canvas.CreateGraphics();

您想要绘制的所有内容都必须存储在Lists个类中,足以容纳您需要的所有信息。

如果您只在一支笔中绘制Rectangles List<Rectangle>就足够了,但对于其他形状和笔,您需要创建一个class来保存这些数据。

现在你可以:

  • Paint事件中全部绘制它们,迭代List<your DrawItemClass>
  • 删除或设置列表中您不想再绘制的项目。