-2
今天,我已經試過的Visual Studio +的WinForms(我一直在使用Xamarin) 我不使用設計器,只需要創建空的項目和環節所需的庫。 因此,我的計時器不能正常工作,它只能以最小化的形式打勾。Timer未勾選
App.cs
using System;
using System.Windows.Forms;
namespace Line
{
class App
{
[STAThread]
public static void Main()
{
Application.Run(new Window());
}
}
}
Window.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;
namespace Line
{
class Window : Form
{
Timer timer;
PictureBox pictureBox;
Bitmap bmp;
public struct Circle
{
public PointF position;
public SizeF size;
};
List<Circle> circles;
public Window()
{
this.Text = "Line";
this.Size = SizeFromClientSize(new Size(640, 480));
pictureBox = new PictureBox();
pictureBox.Dock = DockStyle.Fill;
pictureBox.BackColor = Color.White;
pictureBox.Paint += new PaintEventHandler(pictureBox_Paint);
this.Controls.Add(pictureBox);
this.Load += new EventHandler(Window_Load);
this.Resize += new EventHandler(Window_Resize);
circles = new List<Circle>();
timer = new Timer();
timer.Interval = 15;
timer.Enabled = true;
timer.Tick += new EventHandler(timer_Tick);
}
private void pictureBox_Paint(object sender, PaintEventArgs e)
{
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.Black);
foreach (Circle c in circles)
{
g.DrawEllipse(Pens.White, new RectangleF(c.position, c.size));
}
pictureBox.Image = bmp;
}
private void timer_Tick(object sender, EventArgs e)
{
Circle c;
Console.WriteLine("Works");
for (int i = 0; i < circles.Count; i++)
{
c = circles[i];
c.size.Width = (c.size.Width > 200) ? 100 : c.size.Width + 1;
circles[i] = c;
}
pictureBox.Invalidate();
}
private void Window_Load(object sender, EventArgs e)
{
bmp = new Bitmap(this.Width, this.Height);
circles.Add(new Circle());
Circle c = circles[0];
c.position = new PointF(100, 100);
c.size = new SizeF(100, 100);
circles[0] = c;
}
private void Window_Resize(object sender, EventArgs e)
{
bmp = new Bitmap(this.Width, this.Height);
pictureBox.Invalidate();
}
}
}
相同的代碼在Xamarin工作得很好。
爲什麼你會不使用設計師?有一個完整的部分類被創建,你不想自己寫。 – krillgar
你完全濫用'Paint'。用'e.Graphics'繪製;根本不要使用「PictureBox」或「Image」或「Bitmap」。 – SLaks
我使用位圖,因爲PictureBox支持雙緩衝,如果我只使用圖形,那麼會出現「輕彈」。 – IOD