我需要在C#中画一个Fermat螺旋。我做到了,但是我希望我的绘图可以在PictureBox中填充,无论实际尺寸有多大。
public void DrawSpiral(double delta, double numCycles, int oX, int oY, SpiralType spiralType, Color color, Graphics g)
{
double a = Convert.ToInt32(textBox1.Text);
Pen p = new Pen(color, 1);
double prevX = oX;
double prevY = oY;
double X = oX;
double Y = oY;
double fi = Convert.ToInt32(textBox2.Text);
double radius = 0;
while (fi <= (numCycles * 360))
{
fi += delta;
if (spiralType == SpiralType.FermaPlus)
{
radius = a * Math.Sqrt(fi);
}
else if (spiralType == SpiralType.FermaMinus)
{
radius = -a * Math.Sqrt(fi);
}
prevX = X;
prevY = Y;
X = (radius * Math.Cos(fi / 180 * Math.PI)) + oX;
Y = (radius * Math.Sin(fi / 180 * Math.PI)) + oY;
g.DrawLine(p, (float)prevX, (float)prevY, (float)X, (float)Y);
}
}
private void DrawButton_Click(object sender, EventArgs e)
{
pictureBox1.Refresh();
Graphics g = pictureBox1.CreateGraphics();
DrawSpiral(2, 5, 150, 150, SpiralType.FermaPlus, Color.Blue, g);
DrawSpiral(2, 5, 150, 150, SpiralType.FermaMinus, Color.Red, g);
}
那么,我应该怎样做才能让我的绘图完全填充在PictureBox中。
答案 0 :(得分:3)
这是一种方法:
更改DrawSpiral
的签名以包含ClientSize
的{{1}},而不是某些中心坐标:
PictureBox
然后动态计算中心:
public void DrawSpiral(double delta, double numCycles, int spiralType,
Color color, Graphics g, Size sz)
接下来计算因子 int oX = sz.Width / 2;
int oY = sz.Height / 2;
double prevX = oX;
double prevY = oY;
double X = oX;
double Y = oY;
:
a
最后从 a = sz.Width / 2 / Math.Sqrt( numCycles * 360);
事件调用 方法,并传递有效的Paint
对象:
Graphics
调整private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Size sz = pictureBox1.ClientSize;
DrawSpiral(2, 5, SpiralType.FermaPlus, Color.Blue, g, sz);
DrawSpiral(2, 5, SpiralType.FermaMinus, Color.Red, g, sz);
}
的大小后,它仍然会用相同数量的循环填充该区域..:
一些注意事项:
首先在PictureBox
中收集数据,然后使用List<Point> points
我在计算因子DrawLines(pen, points.ToArray())
时只使用width
。使用a
始终将其放入非方框中!
我保留了偏移量计算;但你可以做一个Math.Min(sz.Width, sz.Height)
..
调整大小后,g.TranslateTransform()
将会PictureBox
。如果您更改了任何参数,请拨打Invalidate/Refresh
来接听它们!