I'm trying to create pictureBox with which I could zoom in/out to cursor, like google maps.
Some code:
int viewRectWidth;
int viewRectHeight;
public float zoomshift = 0.05f;
int xForScroll;
int yForScroll;
float zoom = 1.0f;
public float Zoom
{
get { return zoom; }
set
{
if (value < 0.001f) value = 0.001f;
zoom = value;
displayScrollbar();
setScrollbarValues();
Invalidate();
}
}
Size canvasSize = new Size(60, 40);
public Size CanvasSize
{
get { return canvasSize; }
set
{
canvasSize = value;
displayScrollbar();
setScrollbarValues();
Invalidate();
}
}
Bitmap image;
public Bitmap Image
{
get { return image; }
set
{
image = value;
displayScrollbar();
setScrollbarValues();
Invalidate();
}
}
InterpolationMode interMode = InterpolationMode.HighQualityBilinear;
public InterpolationMode InterpolationMode
{
get { return interMode; }
set { interMode = value; }
}
public ZoomablePictureBox()
{
InitializeComponent();
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint |
ControlStyles.ResizeRedraw | ControlStyles.UserPaint |
ControlStyles.DoubleBuffer, true);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if(image != null)
{
Rectangle srcRect, distRect;
Point pt = new Point((int)(hScrollBar1.Value / zoom), (int)(vScrollBar1.Value / zoom));
if (canvasSize.Width * zoom < viewRectWidth)
srcRect = new Rectangle(0, 0, canvasSize.Width, canvasSize.Height);
else srcRect = new Rectangle(pt, new Size((int)(viewRectWidth / zoom), (int)(viewRectHeight / zoom)));
distRect = new Rectangle((int)(-srcRect.Width / 2), -srcRect.Height / 2, srcRect.Width, srcRect.Height);
Matrix mx = new Matrix();
mx.Scale(zoom, zoom);
mx.Translate(viewRectWidth / 2.0f, viewRectHeight / 2.0f, MatrixOrder.Append);
Graphics g = e.Graphics;
g.InterpolationMode = interMode;
g.Transform = mx;
g.DrawImage(image, distRect, srcRect, GraphicsUnit.Pixel);
}
}
Now I need mouse wheel event to zoom and scroll to mouse point, and I just can't figure out formula to what values I should set scrollBars.
private void onMouseWheel(object sender, MouseEventArgs e)
{
if (ModifierKeys == Keys.Control)
{
this.Zoom += e.Delta / 120 * this.zoomshift;
vScrollBar1.Value = ?;
hScrollBar1.Value = ?;
}
}
any help would be appreciated.
Regards, Tomas