[英]Resize graphics to fit in PictureBox
我需要用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中。
這是一種方法:
更改DrawSpiral
的簽名以包括PictureBox
的ClientSize
而不是某些中心坐標:
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())
可以提高質量和性能
當我計算因子a
時,我只使用了width
。 使用Math.Min(sz.Width, sz.Height)
始終將其放入非方形框中!
我把你的偏移計算留在了原地; 但你可以改為做一個g.TranslateTransform()
..
調整大小后 , PictureBox
將自動Invalidate/Refresh
。 如果您更改任何參數,請調用Invalidate
來獲取它們!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.