[英]C# graphics slow
我在Visual Studio 2013中學習C#,遇到了問題。
我正在畫一堆在屏幕上移動的點(現在是20)。 在刷新之間(每毫秒),我要求清除圖形。 但是,這會導致清除后我正在繪制的點被擦除。 最終的結果是這些點似乎在屏幕上閃爍。 我是一名Java程序員,我以使用Java的方式來處理此圖形。 錯了嗎 我該怎么做才能解決我的問題?
我相信該錯誤是由於我的tick方法運行大約需要9毫秒而導致的。
這是我的代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
namespace AstroidBlast {
public partial class Form1 : Form {
Random r = new Random();
System.Windows.Forms.Timer gameTimer = new System.Windows.Forms.Timer();
Particle[] particles = new Particle[20];
int tick = 0;
public Form1() {
InitializeComponent();
gameTimer.Interval = 1;
gameTimer.Tick += new EventHandler(gameTimer_Tick);
gameTimer.Start();
this.Width = 800;
this.Height = 600;
for (int i = 0; i < particles.Length; i++) {
particles[i] = new Particle(new Velocity(r.Next(0, 360) * (Math.PI / 180), r.NextDouble() *.75 + 0.25), 100, 100, r);
}
}
private void Form1_Load(object sender, EventArgs e) {}
private void gameTimer_Tick(object sender, EventArgs e) {
Graphics g = this.CreateGraphics();
Stopwatch s = new Stopwatch();
s.Start();
g.Clear(Color.White);
for (int i = 0; i < particles.Length; i++)
particles[i].draw(g, Math.Sqrt(tick++));
s.Stop();
Debug.Print(s.ElapsedMilliseconds + "");
}
}
class Particle {
static SolidBrush brush = new SolidBrush(Color.FromArgb(40, 40, 40));
Random r;
Velocity velocity;
double x, y;
public Particle(Velocity v, double x, double y, Random r){
velocity = v;
this.x = x;
this.y = y;
this.r = r;
}
public void draw(Graphics g, double t) {
g.FillEllipse(brush, (int)(velocity.speed * t * Math.Cos(velocity.angle) + x), (int)(velocity.speed * t * Math.Sin(velocity.angle) + y), 8, 8);
}
}
class Velocity {
public double angle, speed;
public Velocity(double angle, double speed) {
this.angle = angle;
this.speed = speed;
}
}
}
不,通常這不是繪制C#的正確方法。
您應該重寫OnPaint
事件,該事件為您提供了Graphics
對象並對其進行繪圖。 在計時器刻度內,您可以使要重繪的全部或部分區域Invalidate
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
// draw here
}
private void gameTimer_Tick(object sender, EventArgs e)
{
this.Invalidate(); // optionally, provide the area to invalidate for better performance
}
通過告訴您的表單使用DoubleBuffered
還可以提高性能/減少閃爍
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true
}
通過上述更改重新生成代碼不會引起明顯的閃爍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.