I have a PictureBox
inside a Panel
, and I have implemented the zoom function with a TrackBar
.
When I increase (or decrease) the PictureBox
, the position of the image remain fixed on the left side of the PictureBox
.
See the example to better understand the problem.
What I want is the possibility to relocate the image compared to the center of the Panel
. See the following example
For example I tried to define the PictureBox
X origin in this way:
- before the zoom I calculate the distance (Δdx) between the origin of the
PictureBox
(x0) and the center of thePanel
(x1). - I increase the distance with the zoom factor (Δdx').
- I calculate the new origin of the image (x0') as x1 - Δdx'
I do the same with Y and I define the new PictureBox
location with x0' and y0'.
Here the code:
// new image width after the zoom
double width = pbImg.Image.Width + (pbImg.Image.Width * trackbar.Value / 100);
// new image height after the zoom
double height = pbImg.Image.Height + (pbImg.Image.Height * trackbar.Value / 100);
// panel center
int cX = panel.Width / 2;
int cY = panel.Height / 2;
// actual origin for the picturebox
int imgX = pbImg.Location.X;
int imgY = pbImg.Location.Y;
// distance the panel center and the picturebox origin
int distFromXc = cX - imgX;
int distFromYc = cY - imgY;
// new distance with zoom factor
distFromXc = distFromXc + (distFromXc * trackbar.Value / 100);
distFromYc = distFromYc + (distFromYc * trackbar.Value / 100);
// new origin point for the picturebox
int pbX = (cX - distFromXc);
int pbY = (cY - distFromYc);
// new dimension for the picturebox
pbImg.Size = new Size(Convert.ToInt32(width), Convert.ToInt32(height));
// relocate picturebox
Point p = new Point(pbX, pbY);
pbImg.Location = p;
I tried to modify this C#
code, but I’m not familiar with it.
In my case I want to manage the Picturebox
and the image inside it as the same object (if it’s possible).
What I want is the possibility to increase (or decrease) the Picturebox
(and the image inside) but I want the Picturebox
to stay centered where it currently is.
The SizeMode
of the picture is StretchImage
.
The Trackbar
has 0% as he minimum value and 100% as the maximum.
The size of the Picturebox
, and the image isnside, can be variable, I receive the images from another software.
A zoomed Picturebox
can be bigger than Panel
, but it’s not a problem, because I can move it.
The problems are the following:
1. If i use the code I wrote above, the reposition seems to work, but the Picturebox
isn’t resized.
2. If I use a fixed value for the origin of the Picturebox (for example Point p = new Point(50, 50)
), the resize works but obviously the position of the Picturebox
is fixed.