Tuesday, December 31, 2013

How to determine mouse position in zoomed image


public Form1()
{

InitializeComponent();
img = Image.FromFile( imagefilename );
zoom = ((float)pictureBox.Width / (float)img.Width) * (img.HorizontalResolution / g.DpiX);
}


protected override void OnMouseWheel(MouseEventArgs e)
{
float oldzoom = zoom;

if (e.Delta > 0)
{
zoom += 0.1F;
}

else if (e.Delta < 0)
{
zoom = Math.Max(zoom - 0.1F, 0.11F);
}



// ... some code



// handle selection box
if (rubberBandRect.Size.Width != 0) {
float ppd = img.HorizontalResolution / g.DpiX;


float a420x = ((float) rubberBandRect.X - oldImgX * oldzoom ) / oldzoom * ppd;
float a420y = ((float) rubberBandRect.Y - oldImgY * oldzoom ) / oldzoom * ppd;


float a3x = a420x / ppd * (zoom );
float a3y = a420y / ppd * (zoom );

float a6x = imgx * zoom;
float a6y = imgy * zoom;
float npx = a6x + a3x;
float npy = a6y + a3y;

rubberBandRect.X = (int) npx;
rubberBandRect.Y = (int) npy;

float oldWidth = rubberBandRect.Width / oldzoom * ppd;
float oldHeight = rubberBandRect.Height / oldzoom * ppd;

rubberBandRect.Width = (int) ((float) oldWidth / ppd * zoom);
rubberBandRect.Height = (int) ((float) oldHeight / ppd * zoom);
}



private void pictureBox_Paint(object sender, PaintEventArgs e)
{
GraphicsState save = e.Graphics.Save();
e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
e.Graphics.ScaleTransform(zoom, zoom);
e.Graphics.Restore( save );
}




No comments:

Post a Comment