Panel Drawing zoom in C#

前端 未结 2 1365
轮回少年
轮回少年 2020-12-19 16:40

I have a Form that contain a panel, and in this panel I draw shapes, like rectangles and circles, I need to zoom into this shapes, I saw couple options but most of them usin

相关标签:
2条回答
  • 2020-12-19 16:46

    Here is a way to scale the drawing by scaling the Graphics object:

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        g.ScaleTransform(zoom, zoom);
    
        // some demo drawing:
        Rectangle rect = panel1.ClientRectangle;
        g.DrawEllipse(Pens.Firebrick, rect);
        using (Pen pen = new Pen(Color.DarkBlue, 4f)) g.DrawLine(pen, 22, 22, 88, 88);
    
    }
    

    Here we store the zoom level:

    float zoom = 1f;
    

    Here we set it and update the Panel:

    private void trackBar1_Scroll(object sender, EventArgs e)
    {
       // for zooming between, say 5% - 500%
       // let the value go from 50-50000, and initialize to 100 !
        zoom = trackBar1.Value / 100f;  
        panel1.Invalidate();
    }
    

    Two example screenshots:

    Note how nicely this scales the Pen widths as well. Turning on antialiasing would be a good idea..: g.SmoothingMode = SmoothingMode.AntiAlias;

    0 讨论(0)
  • 2020-12-19 17:02

    Since you're drawing from scratch, couldn't you resize you drawing base on zoom factor?

    You could multiply your drawing dimensions by your zoom factor. Assuming your zoom factor would be:

    • 0.5 for 50 % zoom (which would reduce the drawing size)
    • 1.0 for 100% (Real size)
    • 1.5 for 150 % (bigger size), you could calc the width this way:
    object.Width = originalWidth * zoomFactor;
    
    0 讨论(0)
提交回复
热议问题