Замедление анимации в C # - PullRequest
2 голосов
/ 04 июня 2011

У меня есть проект класса, который использует Windows Forms для создания графического интерфейса пользователя, который управляет второй формой.Вторая форма - это DrawingForm с растровым изображением.Используя фонового работника, я рисую случайные непрерывные кривые Безье по всему растровому изображению.Это простая программа, поэтому она может рисовать их быстро, сотни в секунду.Я хотел бы добавить ползунок, который позволил бы мне контролировать скорость рисования линий.Другими словами, я не хочу настраивать каждую кривую, которая будет отображаться на таймере, который заставит ее останавливаться и запускаться сотни раз в секунду.Я исчерпал себя в поиске Google, любые советы о том, как это сделать, было бы здорово.Спасибо!

Редактировать: Вот фрагмент кода.Этот код в моем классе для моей формы рисования.Его конструктор вызывается из моего основного класса GUI / пользовательского контроля.

    // this is the code executed by the background thread
    // it can run continously without hanging the user interface thread
    // except that it draws to a bitmap (with the bMapDC) instead of to the form
    private void backgroundWorkerDrawing_DoWork(object sender, DoWorkEventArgs e)
    {

        for (int i = 0; i < 100000000; i++)
        {
            if (scribbleOn == true)
            {
                curveColor = changeColor(curveColor);
                Pen pen = new Pen(curveColor, penThickness);

                if (i == 0) // initial curve should start in center, the rest of the points will be random
                {
                    lastX = GUI.rand.Next(0, bMapWidth); //used to store the x coordinate where the curve ends
                    lastY = GUI.rand.Next(0, bMapHeight); //used to store the y coordinate where the curve ends

                    bMapDC.DrawBezier(pen, initialX, initialY, GUI.rand.Next(0, bMapWidth), GUI.rand.Next(0, bMapHeight),
                    GUI.rand.Next(0, bMapWidth), GUI.rand.Next(0, bMapHeight), lastX, lastY);
                }

                if (i > 0) // used for all curves after the first one. 
                {
                    int tempX = GUI.rand.Next(0, bMapWidth); //used to store the x coordinate where the curve ends
                    int tempY = GUI.rand.Next(0, bMapHeight); //used to store the y coordinate where the curve ends

                    bMapDC.DrawBezier(pen, lastX, lastY, GUI.rand.Next(0, bMapWidth), GUI.rand.Next(0, bMapHeight),
                    GUI.rand.Next(0, bMapWidth), GUI.rand.Next(0, bMapHeight), tempX, tempY);

                    lastX = tempX; // sets the last x coordinate of the last curve for next loop
                    lastY = tempY;  // sets the last y coordinate of the last curve for next loop
                }
                pen.Dispose(); // free up resources from the pen object
            }   
            else i = 0;
        }
    }

    // timer event handler causes the form to be repreatedly invalidated
    // This causes the paint event handler to keep going off,
    // which causes the bMap that is continously being drawn to
    // by the background thread to be continously redisplayed in the form.
    // We will see other ways to do this that may be better.
    private void timerInvalidate_Tick(object sender, EventArgs e)
    {
        Invalidate();
    }

    private void DrawingForm_Shown(object sender, EventArgs e)
    {
        lock (bMap)
        {
            bMapHeight = bMap.Height;  // set the vars that keep track of the size of the bMap
            bMapWidth = bMap.Width;

            initialX = bMapWidth / 2; // start the curve at the center of the bMap
            initialY = bMapHeight / 2;
            bMapDC = Graphics.FromImage(bMap);  // setup the DC (device context) to allow drawing to the bMap)
            backgroundWorkerDrawing.RunWorkerAsync();   // start the background thread
            timerInvalidate.Enabled = true;  // start the timer that will cause periodic Invalidates
        }
    }

1 Ответ

0 голосов
/ 04 июня 2011

Вы можете сделать нить и использовать сон

private Thread SimulaciaArts;
public Animation(){
public SpleepValue { get; set;}

SimulaciaArts = new Thread(new ThreadStart(simuluj));
}

public void simuluj(){

//anything
Thread.Sleep(SleepValue);

}

и в графическом интерфейсе вы должны использовать делегат

 delegate void Invoker();
 private void setSpeed()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Invoker(setSpeed));
                return;
            }
 Simulation.SleepValue=Speed;
}

Надеюсь, это хорошо.

...