缩放以适合在Winforms Panel c#中绘图

本文关键字:Panel 绘图 Winforms 缩放 | 更新日期: 2023-09-27 18:10:16

我有一个应用程序,可以在面板上绘制许多形状(矩形,直线和圆形)。面板可以放大和缩小这些形状。我要做的是当应用程序被触发时,我需要缩放形状以适合窗口。如何做到这一点,我读了很多关于定义图像的书,但没有读过形状。这是我的快照

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);
    }
}

谢谢

缩放以适合在Winforms Panel c#中绘图

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;