调整图形大小以适合 PictureBox

Resize graphics to fit in PictureBox

我需要在 C# 中绘制费马螺线。我做到了,但我希望我的画被填充到 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 的签名以包含 PictureBoxClientSize 而不是某些中心坐标:

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 事件调用方法 only,传递出有效的 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 的大小后,它仍会用相同数量的循环填充该区域..:[=​​31=]

一些注意事项:

  • 首先在 List<Point> points 中收集数据,然后使用 DrawLines(pen, points.ToArray())

  • 可以提高质量和性能
  • 我在计算因子 a 时只使用了 width。使用 Math.Min(sz.Width, sz.Height) 使其始终适合非方形框!

  • 我保留了您的偏移量计算;但你可以改为 g.TranslateTransform()..

  • PictureBox 将在 调整大小Invalidate/Refresh 自身。如果您更改任何参数,请调用 Invalidate 来获取它们!