我正在尝试开发一个“PictureBox”,它显示一个小圆圈“环绕”一个大圆圈。关键方面是这个小圆圈的位置(以及整体情况)可以根据我每秒进行的半昂贵的硬件调用而改变。我用“AngleValueTextBox”调用来说明。
研究有关该主题的几篇文章,这似乎是正确的方法:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
AngleValueTextBox_TextChanged(null, null); // Why doesn't this make the box appear on program start?
PictureBox.Invalidate(); // Or this?
}
public class CircleCenterClass { public double X; public double Y;
public CircleCenterClass(double X, double Y) { this.X = X; this.Y = Y; }
}
CircleCenterClass GetCenterOfOrbitCircle(CircleCenterClass OrbitCenter, double OrbitRadius, double Angle)
{
CircleCenterClass Result = new CircleCenterClass(0, 0);
Result.X = OrbitCenter.X + OrbitRadius * Math.Sin(Angle * (3.141592654 / 180));
Result.Y = OrbitCenter.Y - OrbitRadius * Math.Cos(Angle * (3.141592654 / 180));
return Result;
}
private void drawPictureBox(Graphics graphics, bool ownGraphics)
{
double Angle= 0;
// Normally this is an expensive hardware call which I don't want to make more than
// once a second.
try {
Double.TryParse(AngleValueTextBox.Text, out Angle);
} catch (Exception e) {
MessageBox.Show("Could not parse Angle " +
AngleValueTextBox.Text);
}
using (Bitmap bitmap = new Bitmap(PictureBox.Width, PictureBox.Height))
{
using (Graphics gx = Graphics.FromImage(bitmap))
{
double OrbitedCircleRadius = 40;
CircleCenterClass OrbitedCircleCenter = new CircleCenterClass(60, 60);
double OrbitingCircleRadius = 7;
Pen MyRedPen = new Pen(Color.Red, 2f);
Brush MyBlackBrush = new SolidBrush(Color.Black);
gx.DrawEllipse(MyRedPen, (Int32)(OrbitedCircleCenter.X - OrbitedCircleRadius),
(Int32)(OrbitedCircleCenter.Y - OrbitedCircleRadius),
(Int32)(2 * OrbitedCircleRadius),
(Int32)(2 * OrbitedCircleRadius));
CircleCenterClass CircleCenter = GetCenterOfOrbitCircle(
OrbitedCircleCenter, OrbitedCircleRadius,
Angle);
gx.FillEllipse(MyBlackBrush, (Int32)(CircleCenter.X - OrbitingCircleRadius),
(Int32)(CircleCenter.Y - OrbitingCircleRadius),
(Int32)(2 * OrbitingCircleRadius),
(Int32)(2 * OrbitingCircleRadius));
// Draw Electronics box.
Graphics g = PictureBox.CreateGraphics();
g.Clear(BackColor);
g.DrawImage(bitmap, 0, 0);
}
}
}
private void PictureBox_Paint(object sender, PaintEventArgs e)
{
drawPictureBox(e.Graphics,false);
}
private void AngleValueTextBox_TextChanged(object sender, EventArgs e)
{
drawPictureBox(PictureBox.CreateGraphics(), true);
}
}
关键问题:
我最初无法显示图片(即当 GUI 启动时)。我尝试将事件添加到我的 Form 构造函数(如您所见)但没有运气。什么是“正确”的方式?
有没有更好的方法来绘制不断变化的图形?