how to zoom in&out and keep picture aspect ratio?

Farshad Valizade 501 Reputation points
2025-01-26T04:42:34.29+00:00

hi

I have a winform app to display a pdf file into a picturebox control.

When the user presses the left mouse button and moves the mouse until the mouse is released, a line is drawn.

The start and end positions of each line are stored in a list. I want the image to be larger or smaller when the zoom in and zoom out buttons are selected, but the position of the drawn lines also changes but does not move (they become smaller or larger in proportion to the zoom). But my output is as you can see :

Normal Mode:

1

after zoom in :

2

my code :

pdfViewer.SizeMode = PictureBoxSizeMode.StretchImage;

 private void RenderPdfPage(int pageIndex, int dpi)
 {
     if (pdfDocument == null || pageIndex < 0 || pageIndex >= pdfDocument.PageCount)
     {
         MessageBox.Show("Invalid page index.");
         return;
     }
     // Render the page as a Bitmap
     using (var pageImage = pdfDocument.Render(pageIndex, dpi, dpi, PdfRenderFlags.CorrectFromDpi))
     {
         // Load an image
         currentImage = new Bitmap(pageImage);
         // Configure PictureBox                
         pdfViewer.Image = currentImage;
         panel_main.AutoScrollMinSize = new Size(pdfViewer.Width, pdfViewer.Height);
         zoomFactor = 1.0f;
     }
 }

        private void Zoom(float factor)
        {
            if (currentImage == null) return;
            zoomFactor *= factor;
            pdfViewer.SizeMode = PictureBoxSizeMode.StretchImage;
            pdfViewer.Width = (int)(pdfViewer.Image.Width * zoomFactor);
            pdfViewer.Height = (int)(pdfViewer.Image.Height * zoomFactor);
            panel_main.AutoScrollMinSize = new Size(pdfViewer.Width, pdfViewer.Height);
            shape.StartPoint = new Point(
                (int)(shape.StartPoint.X * factor),
                (int)(shape.StartPoint.Y * factor)
            );
            shape.EndPoint = new Point(
                (int)(shape.EndPoint.X * factor),
                (int)(shape.EndPoint.Y * factor)
            );
            pdfViewer.Invalidate();
        }
 private void pdfViewer_Paint(object sender, PaintEventArgs e)
 {
	foreach (var lines in history)
	{
			Point scaledStart = new Point((int)(lines.Field<int>("X1") * zoomFactor), (int)(lines.Field<int>("Y1") * zoomFactor));
			Point scaledEnd = new Point((int)(lines.Field<int>("X2") * zoomFactor), (int)(lines.Field<int>("Y2") * zoomFactor));
			e.Graphics.DrawLine(Pens.Black, scaledStart, scaledEnd);	
	}
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,237 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.