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

时间:2015-08-27 14:36:52

标签: c# winforms zoom panel

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

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

谢谢

1 个答案:

答案 0 :(得分:1)

将形状绘制到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;