Pan
When an image is bigger than the viewport, we tend to scroll the image to see parts that are not visible. To pan or scroll images in a viewport, applications provide different types of user interfacesfor example, scroll bars. Some applications provide mouse-based scrolling. With mouse-based schemes, you normally hold the mouse down and drag the image so that you can view the desired portion of the image. In our design, however, we'll separate the GUI from the controller. The controller will have the logic to scroll on an image canvas, and it will accept input from any type of user interface.
Let's discuss the requirements and design an interface named ScrollController. Figure 7.6 shows how images are panned, or scrolled. The position at which you click the mouse is the anchor point, and as you drag, the current mouse position is the current position of the image. The pan offset is the displacement between the current position and the anchor point. The current image is drawn with this offset from the previous position.
FIGURE 7.6 Panning an image
To hold this displacement, let's specify a property named panOffset. The set and get methods for this property are
public void setPanOffset(Point panOffset);
public Point getPanOffset();
We need a method that initiates the scrolling. This method should set the anchor point. Let's call this method startScroll():
public void startScroll(int x, int y)
We also need a method that stops the scrolling:
public void stopScroll()
When the image is scrolled, it is painted at a new position. The paintImage() method we defined in the ImageDisplay interface will not suffice to accomplish this task. So let's specify a method for this purpose, with the displacement in the x and y directions as its inputs:
public void scroll(int xOffset, int yOffset);
This method paints the current image at an offset of xOffset and yOffset from the previous position in the x and y directions, respectively.
The ScrollController interface, shown in Listing 7.6, contains all the methods defined here.
LISTING 7.6 The ScrollController interface
public interface ScrollController { public void setPanOffset(Point panOffset); public Point getPanOffset(); public void startScroll(int x, int y); public void scroll(int x, int y); public void stopScroll(); }
Implementing Pan
Now that we have designed an interface to implement scrolling (panning), let's implement a mouse-driven scroll feature. It will have two classes:
Scroll. This class will control scrolling by implementing the ScrollController interface. Scroll will operate on an image canvas, so it needs to hold a reference to an object that implements the ImageManipulator interface.
ScrollGUI. This class will accept user input and pass it on to Scroll Controller. In the case of mouse-driven scrolling, ScrollGUI must receive mouse and mouseMotion events from ImageManipulator.
Figure 7.7 shows a design similar to model-view-controller (MVC) architecture 1 for scrolling. The ScrollGUI object receives the mouse positions through mouse and mouseMotion events. It passes the mouse positions as pan offset to the ScrollController interface, which modifies the current transformation to take the translation into account.
FIGURE 7.7 The data flow for scrolling
We'll follow the same design pattern for all the other manipulation functions. This pattern clearly separates the GUI and the application logic, so you are free to replace ScrollGUI with another class for a different type of GUI.
Two schemes are popular for scrolling images in a viewport:
Using scroll bars
Using mouse-driven interfaces
Because we use the mouse-driven interface in this book, let's look at how a mouse-driven client object must interact with a Scroll object.
The Scroll object must remember two positions: the anchor point and the current position of the image. When the mouse is pressed, the mousePressed() method of a client object must call startScroll(int x, int y) and pass the current coordinates of the mouse as the input parameters. The startScroll() method must save this position as the anchor point. Whenever the mouse is dragged, the mouseDragged() method of the client object must call scroll(int x, int y) and pass the current position of the mouse as input parameters. The scroll() method must compute the displacement between the current position of the mouse and the anchor position. It must then pass this displacement to the ImageManipulator object so that it can paint the image at the current mouse position. When the mouse button is released, the mouseReleased() method of the client object must call stopScroll().
Listing 7.7 shows the code for Scroll.
LISTING 7.7 The Scroll class
package com.vistech.imageviewer; import java.io.*; import java.awt.*; import java.awt.image.*; import java.util.*; import java.awt.geom.*; public class Scroll implements ScrollController { protected AffineTransform atx = new AffineTransform(); protected Point panOffset = new Point(0,0); private Point diff = new Point(0,0); private Point scrollAnchor = new Point(0,0); protected ImageManipulator imageCanvas; public Scroll() {} public Scroll(ImageManipulator imageCanvas) { this.imageCanvas = imageCanvas; } public void setImageManipulator(ImageManipulator imageCanvas){ this.imageCanvas = imageCanvas; } public void setPanOffset(Point panOffset){ this.panOffset = panOffset; imageCanvas.setPanOffset(panOffset); } public Point getPanOffset(){return panOffset; } public void translateIncr(double incrx, double incry) { atx.translate(incrx, incry); imageCanvas.applyTransform(atx); } public void translate(double diffx, double diffy) { double dx = diffx -panOffset.x; double dy = diffy -panOffset.y; panOffset.x = (int)diffx; panOffset.y = (int)diffy; translateIncr(dx,dy); } public void resetAndTranslate(int dx, int dy) { atx.setToTranslation((double)dx, (double)dy); imageCanvas.applyTransform(atx); } public void scroll(int x, int y){ if((x <0 )|| (y<0)) return; try { Point2D xy = null; xy = atx.inverseTransform((Point2D)(new Point(x,y)), xy); double ix = (xy.getX()-scrollAnchor.x); double iy = (xy.getY()-scrollAnchor.y); translateIncr(ix,iy); }catch(Exception e) {System.out.println(e);} } public void startScroll(int x, int y){ atx = imageCanvas.getTransform(); // Create a new anchor point so that every time mouse button is clicked, // the image does not move, but instead the anchor point moves. try { Point2D xy = null; xy = atx.inverseTransform((Point2D)(new Point(x,y)), xy); scrollAnchor = new Point((int)(xy.getX()),(int)(xy.getY())); imageCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); }catch(Exception e) {System.out.println(e);} } public void stopScroll(){ imageCanvas.setCursor(Cursor.getDefaultCursor());} public void reset() { scrollAnchor = new Point(0,0); diff = new Point(0,0); } }
The Scroll class implements the ScrollController interface. Note that Scroll's constructor takes the ImageManipulator object as an input. This means you can pass any component class that implements the ImageManipulator interface as a parameter to this constructor.
The Scroll object gets the current transformation from the canvas, concatenates it with the transformation generated for the translation, and sets this concatenated transformation as the current transformation of the canvas. Let's look at Scroll's methods.
Scrolling
The startScroll() method first computes the anchor position and assigns it to the variable scrollAnchor. The position passed as an input parameter to startScroll() is in the user coordinate space. These coordinates need to be converted to the image space because the displayed image might have already undergone some transformations. User space is converted to image space through the inverse transformation.
What would happen if this transformation were not done? You would get different results, depending on the transformation(s) already applied to the image. If the image were flipped right to left, it would move in the opposite direction along the x-axis; that is, if you tried to pan the image left to right, it would move right to left. If the image were rotated, it would move in the direction of the rotation when you tried to pan along the x- or y-axis. Inverse transformation solves this problem. The startScroll() method also launches a new cursor to indicate that the image is being panned.
The scroll() method converts the input coordinates to the image space and computes the displacement from the anchor point. This displacement is passed to the translateIncr() method, which performs the actual translation of the image. The stopScroll() method is called when the mouse is released, and it returns the original cursor.
Next we'll look at the translation-related methods in more detail.
Translation
Applying translation makes the image move. The translateIncr() method takes translation increments as input parameters. For instance, if an image is moved to position P(x′,y′) from P(x,y), the translation parameters are the displacements from P(x,y) to P(x′,y′). The reason is that the current transformation, which is contained in the atx variable, has already taken into account the translation to P(x,y) from the original position.
As stated earlier, if the translation parameters are the coordinates from the user space (i.e., viewport), the inverse transformation needs to be applied to these coordinates so that they are in atx space.
The translate() method does the same thing as the translateIncr() method, but it takes the absolute translation from the anchor point. This method resets atx and sets the translation to the parameters specified in the inputs. It calls the setToTranslation() method of the AffineTransform class to reset atx and then translates the images to (dx, dy). Note that the input arguments are of type int. The reason is that the coordinates in the user space are integer types, and these coordinates are expected to be passed directly to this method.
User Interface for Scrolling
As stated earlier, panning in our implementation is performed through mouse and mouseMotion events. The ScrollGUI class must capture these events, which means it needs to implement the MouseListener and MouseMotionListener interfaces. Listing 7.8 shows the implementation.
LISTING 7.8 The ScrollGUI class
package com.vistech.imageviewer; import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ScrollGUI implements MouseListener,MouseMotionListener{ protected ScrollController scrollController; protected boolean scrollOn = true; protected boolean mousePressed = false; public ScrollGUI(ScrollController c){scrollController = c;} public void setScrollOn(boolean onOff){ scrollOn = onOff;} public void init() { setScrollOn(true);} public boolean getScrollOn(){ return scrollOn; } public void startScroll(){ scrollOn = true;} public void reset(){ if(scrollController != null)scrollController.stopScroll(); setScrollOn(false); } public void mousePressed(MouseEvent e) { if(!scrollOn) return; if(mousePressed) return; mousePressed = true; if(SwingUtilities.isLeftMouseButton(e)){ scrollController.startScroll(e.getX(), e.getY()); } } public void mouseReleased(MouseEvent e) { scrollController.stopScroll(); mousePressed = false; } public void mouseClicked(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseDragged(MouseEvent e){ if(SwingUtilities.isLeftMouseButton(e)){ if(scrollOn) scrollController.scroll(e.getX(), e.getY()); } } public void mouseMoved(MouseEvent e){} }
Note that the ScrollGUI constructor takes ScrollController as the input. It communicates with the ImageManipulator object through Scroll (see Figure 7.7).
In order for ScrollGUI to receive mouse and mouseMotion events, a separate object must register ImageManipulator with ScrollGUI. The reason is that both the ImageManipulator and the ScrollController objects are unaware of the ScrollGUI object. This registration needs to be done when ScrollGUI is constructed by an application, as shown here:
ImageManipulator imageCanvas = new ImageCanvas2D(); ScrollController scroll = new Scroll(imageCanvas); ScrollGUI scrollUI = new ScrollGUI(scroll); imageCanvas.addMouseListener(scrollUI);
To refresh your memory, Scroll implements the ScrollController interface, and ImageCanvas2D implements the ImageManipulator interface. These objects can be used as ScrollController and ImageManipulator objects, respectively.
Let's construct a typical sequence of method calls with ScrollGUI, Scroll Controller, and ImageManipulator objects:
The application that needs the scroll feature registers ScrollGUI to receive mouse and mouseMotion events with the ImageManipulator object.
The user presses the left mouse button. The ImageManipulator object, which is the mouse event source, fires the mousePressed event to the ScrollGUI object. The mousePressed() method is invoked when any mouse button is clicked. Because the Scroll class uses only the left mouse button, the isLeftMouse Button() method of the SwingUtilities class checks for this condition; that is, it returns true only when the left mouse button is pressed.
The mousePressed() method calls the startScroll() method in the ScrollController object, which saves the position at which the mouse was pressed as the anchor point (in the variable called anchorPoint).
The user drags the mouse while holding the left mouse down. The ImageManipulator object fires the mouseDragged event, which is received by the mouseDragged() method in ScrollGUI. The mouseDragged() method is called repeatedly as the user drags the mouse.
The mouseDragged() method calls the scroll() method in the Scroll Controller object and passes the current mouse coordinates as its parameters.
The ImageManipulator object paints the current image (i.e., displayImage) at the new position.
The user releases the mouse button, prompting the ImageManipulator object to fire a mouseReleased event. This event is received by the mouseReleased() method.
The mouseReleased() method calls stopScroll() to halt scrolling.