窗口窗体 - 不会画球



所以我在Visual Studio中玩Windows窗体,我正在尝试创建一个简单的程序,它只是使用Graphics类绘制一个球。

以下是球类的代码:

public class Ball
{
public Point centre { get; set; }
public int state { get; set; }
public static int radius = 40;
public void Draw(Graphics g)
{
Brush brush;
brush = new SolidBrush(Color.White);
if(state==0)
{
brush = new SolidBrush(Color.Green);
}
if(state==1)
{
brush = new SolidBrush(Color.Blue);
}
if(state==2)
{
brush = new SolidBrush(Color.Red);
}
g.FillEllipse(brush, centre.X - radius, centre.Y - radius, 2 * radius, 2 * radius);
}
public void Move(Point centre)
{
this.centre = centre;
}
}

这是主程序的类:

public partial class Form1 : Form
{
public Ball ball { get; set; }
public Form1()
{
InitializeComponent();
ball = new Ball();
this.Width = 500;
this.Height = 500;
ball.centre = new Point(250, 250);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
ball.state = 1;
ball.Draw(g);
}
}

但是,每当我启动程序时,它都会成功运行,没有错误,但没有绘制任何内容。

有什么想法吗?

我对Ball类进行了一些修改以管理List<Color>,因此可以在运行时添加更多颜色,一些默认属性和IDisposable支持。

此外,使用设置为AntiAlias的"图形.平滑模式"和设置为"HighQuality"的"图形.合成质量"来增强渲染质量。

public class Ball : IDisposable
{
private SolidBrush brush = null;
private int PrivateState = 0;
public Ball()
: this(new Point(40, 40)) { }
public Ball(Point InitialPosition)
{
this.FillColorList();
this.Centre = InitialPosition;
this.Radius = 40;
this.brush = new SolidBrush(this.Colors[this.PrivateState]);
}
public Point Centre { get; set; }
public int State {
get { return this.PrivateState; }
set { this.PrivateState = (value < this.Colors.Count) ? value : 0; }
}
public int Radius { get; set; }
public List<Color> Colors { get; set; }
private void FillColorList()
{
this.Colors = new List<Color>() { Color.White, Color.Green, Color.Blue, Color.Red };
}
public void Draw(Graphics g)
{
this.brush.Color = this.Colors[this.PrivateState];
g.SmoothingMode = SmoothingMode.AntiAlias;
g.CompositingQuality = CompositingQuality.HighQuality;
g.FillEllipse(brush, Centre.X - Radius, Centre.Y - Radius, 2 * Radius, 2 * Radius);
}
public void Move(Point NewCentre) => this.Centre = NewCentre;
public void Dispose()
{
if (this.brush != null)
this.brush.Dispose();
}
}

Ball对象仍然是属性值,但您可能希望改用 List,以便可以同时管理更多对象。

Form设置:
(请注意,Paint()FormClosing()事件在Form构造函数中注册,因此请确保它们未在其他位置注册,除非出于其他原因使用它们(。

public Form1()
{
InitializeComponent();
ball = new Ball(new Point(250, 250));
ball.State = 1;  // <- Will draw a green ball
this.Paint += (s, e) => { ball.Draw(e.Graphics); };
this.FormClosing += (s, e) => { ball.Dispose(); };
}
public Ball ball { get; set; }

如果要移动Ball对象,请设置新位置并调用this.Invalidate()以引发FormPaint()事件:

ball.Colors.Add(Color.Orange);
ball.State = this.ball.Colors.Count - 1;  // <- Will draw an orange ball
ball.Radius = [new Radius];
ball.Move(new Point([X], [Y]));
this.Invalidate();

相关内容

  • 没有找到相关文章

最新更新