How to implement a ZoomIn & ZoomOut feature

When you think drawing objects on a window, you can think about GDI and its device context API. MFC provided a CDC class of that. But if you need transformation on your drawing objects, there is a better way wich is called GDI+. It provides a lot of API and classes to fill your need.

First, you construct a Graphics object from a device context. In your Draw handler, you just have to write this:

        // Initialize GDI+ graphics context
	Graphics graphics(pDC->m_hDC);

And you tell GDI+ to apply a zoom factor using the ScaleTransform() method:

        graphics.ScaleTransform(m_fZoomFactor, m_fZoomFactor);</pre>

All you have to do is to increment or decrement your float member zoom factor from ZoomIn and ZoomOut handler.

On the OnClick handler, you must be able to select your object with the mouse regardless of the zoom. You have to translate your pixel point to the rendering point that applies the scale transform operation. It is done using the ViewToManager routine call in the click handler:

void CElementManager::OnLButtonDown(CModeler1View* pView, UINT nFlags, const CPoint& cpoint)
{
	CPoint point = cpoint;
	ViewToManager(pView, point);
	m_lastPoint = point;

        ... 

void CElementManager::ManagerToView(CModeler1View * pView, CPoint & point)
{
	CClientDC dc(pView);
	Graphics graphics(dc.m_hDC);
	graphics.ScaleTransform(m_fZoomFactor, m_fZoomFactor);
	Point points[1] = {Point(point.x, point.y)};
	// Transform the points in the array from world to page coordinates.
	graphics.TransformPoints(
		CoordinateSpaceDevice, 
		CoordinateSpaceWorld, 
		points, 
		1);
	point.x = points[0].X;
	point.y = points[0].Y;
}

To find the whole source code to implement a zoomin & zoomout feature, consult my codeplex repository here: http://ultrafluid.codeplex.com/SourceControl/latest#Modeler1/ElementManager.cpp

Advertisements

Tagged: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: