缩放以适合在 Winforms 面板 C# 中绘图

Zoom to fit for drawing in Winforms Panel C#

我有一个应用程序可以在面板上绘制许多形状(矩形、直线和圆形)。 面板可以放大和缩小这个形状。 我想要做的是当应用程序启动时,我需要缩放形状以适应 window。 我该怎么做,我读了很多关于定义的图像而不是形状的文章。 这是我的快照

private void panel1_Paint(object sender, PaintEventArgs e)
{
    SolidBrush brushs = new SolidBrush(Color.White);
    e.Graphics.Clip = new Region(new Rectangle(0, 0, Viewer.Width, Viewer.Height));
    e.Graphics.FillRegion(brushs, e.Graphics.Clip);

    Graphics g = e.Graphics;
    g.TranslateTransform(_ImgX, _ImgY);
    g.ScaleTransform(_Zoom, _Zoom);
    g.SmoothingMode = SmoothingMode.AntiAlias;
    SolidBrush myBrush = new SolidBrush(Color.Black);
    Pen p = new Pen(Color.Red);
    foreach (CircuitData.ResistorRow resistorRow in ResistorData.Resistor)
    {
        RectangleF rec = new RectangleF((float)(resistorRow.CenterX  - resistorRow.Length/ 2), (float)(resistorRow.CenterY - resistorRow.Width/ 2), (float)resistorRow.Length, (float)resistorRow.Width);
        float orientation = 360 - (float)resistorRow.Orientation;
        PointF center = new PointF((float)resistorRow.CenterX, (float)resistorRow.CenterY);
        PointF[] points = CreatePolygon(rec, center, orientation);
        if (!Double.IsNaN(resistorRow.HiX) && !Double.IsNaN(resistorRow.HiY))
        {
            g.FillEllipse(myBrush, (float)resistorRow.HiX  - 2 , (float)resistorRow.HiY - 2, 4, 4);
            g.DrawLine(p, new PointF((float)resistorRow.HiX , (float)resistorRow.HiY ), center);
        }

        g.FillPolygon(myBrush, points);
    }
}

谢谢

将你的形状画到 Metafile 上。它的尺寸将在创建后自动计算。最后,当你将它绘制到面板上时,你可以安全地缩放它。

// the reference Graphics can be taken from your form, its size does not matter
Graphics refGraph = this.CreateGraphics();
IntPtr hdc = refGraph.GetHdc();
Metafile result = new Metafile(hdc, EmfType.EmfOnly, "Shapes");

using (var g = Graphics.FromImage(result))
{
    // draw your shapes here (zooming is not necessary)
    DrawShapes(g);
}

refGraph.ReleaseHdc(hdc);
refGraph.Dispose();

// use this metafile on the panel
return result;