Click here to Skip to main content
13,903,445 members
Click here to Skip to main content
Add your own
alternative version


46 bookmarked
Posted 22 Jan 2008
Licenced CPOL

Image Target Zoom (Pan Zoom)

, 22 Jan 2008
Rate this:
Please Sign up or sign in to vote.
To pan and zoom to a point of interest in an image.



There are several articles about panning and zooming, but to do both of these at the same time can be more useful to the user of your program. But, this does take a little getting used to since you can pan your image too much if you are not used to it.


This is not a new idea, CAD programs use it all the time. But, I don't usually see this feature in imaging software, and since it can be useful, I decided to write one.

Playing With the Code

Try a click drag, to pan the image, and use the mouse wheel to zoom in and out.


Then, try zooming in to a point of interest like an eye or something, and see how the pan-zoom works. It will take some getting used to because you can easily over shoot your target.


Using the Code

Since it is not too long or complicated, I just posted the important parts below. Some things to note are I use buffered graphics for this demo, and I didn't go through extensive error checking situations. I did test this and tried to block some common bugs.

Think of an image on a really big piece of paper, this is our world coordinates. Then, take a window that looks at the world. You can move the window left or right to see different parts of the world. You can move the window forwards or backwards (zooming) to adjust how much of the world you can see. This is the basic concept behind the world coordinates and the viewport coordinates below.

public partial class Form1 : Form
    public class overRidePanel : Panel
        protected override void OnPaintBackground(PaintEventArgs pevent) { }
    Bitmap bitmap;
    BufferedGraphicsContext currentContext;
    BufferedGraphics myBuffer;  
    PointF viewPortCenter;
    float Zoom = 1.0f;
    bool draging = false;
    Point lastMouse;
    public Form1()
        currentContext = BufferedGraphicsManager.Current;
    private void setup(bool resetViewport)
        if (myBuffer != null)
        myBuffer = currentContext.Allocate(this.panel1.CreateGraphics(), 
        if (bitmap != null)
            if (resetViewport)
                SetViewPort(new RectangleF(0, 0, bitmap.Width, bitmap.Height));
    private void SetViewPort(RectangleF worldCords)
       //Find smallest screen extent and zoom to that
        if (worldCords.Height > worldCords.Width)
            //Use With as limiting factor
            this.Zoom = worldCords.Width / bitmap.Width;
            this.Zoom = worldCords.Height / bitmap.Height;
        viewPortCenter = new PointF(worldCords.X +(worldCords.Width / 2.0f), 
                                    worldCords.Y + (worldCords.Height / 2.0f));
        this.toolStripStatusLabel1.Text = "Zoom: " + 
    private void SetViewPort(Rectangle screenCords)
    private void PaintImage()
        if (bitmap != null)
            float widthZoomed = panel1.Width / Zoom;
            float heigthZoomed = panel1.Height / Zoom;
            //Do checks the reason 30,000 is used is because 
            //much over this will cause DrawImage to crash
            if (widthZoomed > 30000.0f)
                Zoom = panel1.Width / 30000.0f;
                widthZoomed = 30000.0f;
            if (heigthZoomed > 30000.0f)
                Zoom = panel1.Height / 30000.0f;
                heigthZoomed = 30000.0f;
            //we stop at 2 because at this point you have almost zoomed into a single pixel
            if (widthZoomed < 2.0f)
                Zoom = panel1.Width / 2.0f;
                widthZoomed = 2.0f;
            if (heigthZoomed < 2.0f)
                Zoom = panel1.Height / 2.0f;
                heigthZoomed = 2.0f;
            float wz2 = widthZoomed / 2.0f;
            float hz2 = heigthZoomed / 2.0f;
            Rectangle drawRect = new Rectangle(
                (int)(viewPortCenter.X - wz2),
                (int)(viewPortCenter.Y - hz2),
            //this.toolStripStatusLabel1.Text = "DrawRect = " + drawRect.ToString();
            myBuffer.Graphics.Clear(Color.White); //Clear the Back buffer
            //Draw the image, Write image to back buffer, and render back buffer
                     this.panel1.DisplayRectangle, drawRect, GraphicsUnit.Pixel);
           this.toolStripStatusLabel1.Text = "Zoom: " + 
                    ((int)(this.Zoom * 100)).ToString() + "%";
    private void openToolStripMenuItem_Click(object sender, EventArgs e)
        if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            bitmap = (Bitmap)Bitmap.FromFile(openFileDialog1.FileName);
    private void Form1_Resize(object sender, EventArgs e)
    private void panel1_Paint(object sender, PaintEventArgs e)
    private void panel1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
        //the 1200.0f is any-number it just seem to work well so i use it.
        Zoom += Zoom * (e.Delta / 1200.0f);
        if (e.Delta > 0)
        //I prefer to use the targe zoom when zooming in only, 
        //remove "if" to have it apply to zoom in and out
            viewPortCenter = new PointF(viewPortCenter.X + 
               ((e.X - (panel1.Width / 2)) /(2* Zoom)), viewPortCenter.Y + 
               ((e.Y - (panel1.Height/2)) / (2*Zoom)));
    private void panel1_MouseDown(object sender, MouseEventArgs e)
        if (e.Button == MouseButtons.Left)
            draging = true;
    private void panel1_MouseMove(object sender, MouseEventArgs e)
        if (draging)
            viewPortCenter = new PointF(viewPortCenter.X + 
              ((lastMouse.X - e.X)/Zoom), viewPortCenter.Y + ((lastMouse.Y- e.Y)/Zoom));
        lastMouse = e.Location;

    private void panel1_MouseUp(object sender, MouseEventArgs e)
        if (e.Button == MouseButtons.Left)
            draging = false;

Points of Interest

A couple of things. First, you will notice that zooming in can be blocky or clunky at times; this is because the pan is moving large amounts. I reduced this by dividing by 2, but it is noticeable. To fix this and make it more smooth, you can either make the maximum pan amount a constant or some proportion of the zoom level. The method posted above accomplished the goal, so I did not pursue the finer details. Note that I create a class whose entire existence and purpose is to override the OnPaintBackground of the standard Panel object. This is done to remove the flicker created by a normal Panel doing the background drawing.


This is the second program like this. Since this version performs better, I posted it.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

United States United States
Currently I work on industrial machinery as a mechanic. I have a few other things on my resume before that are mostly computer related. I have been writing programs in various languages for about 10 years. The single most complex thing I have ever encountered as a programmer, an engineering student, a Christian, a husband, a soldier, and father is, Jesus The Christ, and the book called The Bible. It is like a masterful fractal, but like a graphical representation of a fractal you do not have to understand the math to see how simple, beautiful, and complex it is. Yes, the physical bible is a bunch of words on paper. However, to understand what The Bible says is a scary thing. The world you now live in becomes like a movie studio set, of plywood cutouts. And to look behind the cutout and understand that things are not what they seem is a real mind bender. I could keep going, but the Bible is the smallest most efficient way to communicate the information inside. Note: It is easy to read The Bible and not understand what it means. It is impossible to understand The Bible unless God allows you to, I am not being impetuous, but until you find your life the things you say and do, today, in that book. You may close your eyes and think you know what it means to be blind, but if you have ever been blind you don't 'think you know' you understand.

You may also be interested in...

Comments and Discussions

Questionrotate image Pin
cerezaei12-May-12 19:37
membercerezaei12-May-12 19:37 
GeneralMy vote of 4 Pin
itsme_johar20-Oct-11 4:41
memberitsme_johar20-Oct-11 4:41 
QuestionZoom percentage [modified] Pin
JoaoOliv14-Apr-11 2:15
memberJoaoOliv14-Apr-11 2:15 
AnswerRe: Zoom percentage Pin
Coxianuk23-May-11 23:27
memberCoxianuk23-May-11 23:27 
Questionpanel qns Pin
louz906-Dec-10 21:57
memberlouz906-Dec-10 21:57 
QuestionHow can I create OverRidePanel ? Pin
breakid5-Sep-10 13:46
memberbreakid5-Sep-10 13:46 
QuestionHow Does the Pixels Map After Zooming In/Out Pin
Ravith Hansraj27-Jan-10 0:29
memberRavith Hansraj27-Jan-10 0:29 
Questionneed some help modifying the code! Pin
Fadik15-Nov-09 9:16
memberFadik15-Nov-09 9:16 
QuestionRe: need some help modifying the code! Pin
JoaoOliv27-Apr-11 8:01
memberJoaoOliv27-Apr-11 8:01 
GeneralGreat Job ... but something needed to make it start. Pin
George_micom8-Mar-09 20:44
memberGeorge_micom8-Mar-09 20:44 
QuestionHow to view the designer form Pin
Member 43224713-Feb-09 0:56
memberMember 43224713-Feb-09 0:56 
GeneralPanel1 Control Pin
kjward9-Dec-08 10:45
memberkjward9-Dec-08 10:45 
GeneralRe: Panel1 Control Pin
tal-rath7-Jul-09 1:55
membertal-rath7-Jul-09 1:55 
GeneralRe: Panel1 Control Pin
Tien Vung2-May-11 4:58
memberTien Vung2-May-11 4:58 
GeneralRe: Panel1 Control Pin
Coxianuk23-May-11 23:34
memberCoxianuk23-May-11 23:34 
GeneralRe: Panel1 Control Pin
inzonha8-May-14 5:06
memberinzonha8-May-14 5:06 
GeneralUsing Mouse clicks Pin
Nippo6-Nov-08 22:24
memberNippo6-Nov-08 22:24 
GeneralRe: Using Mouse clicks Pin
Tony Mamacos30-Sep-09 1:05
memberTony Mamacos30-Sep-09 1:05 
Generalscroll bar Pin
smsurendar11-Aug-08 21:03
membersmsurendar11-Aug-08 21:03 
i want to scroll bar should be their in the project.. how will be do
GeneralRe: scroll bar Pin
algates002723-Nov-08 23:01
memberalgates002723-Nov-08 23:01 
GeneralFor ScrollBar Pin
Vengatesan C10-Aug-08 22:07
memberVengatesan C10-Aug-08 22:07 
Generalscroll bar with pan zoom Pin
algates002710-Aug-08 1:23
memberalgates002710-Aug-08 1:23 
QuestionImage dislocates on zooming.. Pin
zainy16-Apr-08 1:19
memberzainy16-Apr-08 1:19 
QuestionRe: Image dislocates on zooming.. Pin
JoaoOliv27-Apr-11 7:58
memberJoaoOliv27-Apr-11 7:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190306.1 | Last Updated 22 Jan 2008
Article Copyright 2008 by LowlyServ-Ant
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid