Home > Articles > Programming > Java

This chapter is from the book

Rotation, Flip, and Shear

Now that we have described the pan and zoom features in detail, it's time to look at other manipulation functions, which include rotate, flip, and shear. For the sake of convenience, instead of building individual interfaces for each of these functions, we'll build a common interface called GeomManipController for all of them. Again, we'll use the same design pattern we used for scroll and zoom. As mentioned earlier, with this design pattern the GUI is separated from control logic. Let's look at the manipulation operations one by one.

Rotation

Rotation may not be used as frequently as pan and zoom. Nevertheless, it is important to have it in your image viewer. Typically, rotation is performed around the midpoint of the image, but our interface can provide a method that specifies the rotation center. First, let's specify the get and set methods for the rotation angle property:

  • public double getRotationAngle();

  • public void setRotationAngle(double theta);

Here are the methods that perform rotation:

  • public void rotate(double theta);

  • public void rotate(double theta, int rotCenterX, int rotCenterY);

The first method rotates the image around the midpoint of the image. The second one rotates the image around a point specified by the input parameters.

Flip

We discussed the fundamentals of flip in Chapter 4. The method for flipping an image at any position or at any state is

  • public void flip(int flipMode)

The flipMode parameter can be any one of the four values defined in the FlipMode class (see Chapter 6).

Shear

Just as we specified the magFactor property for the scaling operation, for shear we'll specify the shearFactor property. The get and set methods for this property are

  • public double getShearFactor();

  • public void setShearFactor(double shear);

The method for shearing an image at any stage of the manipulation is

  • public void shear(double shx, double shy);

The shx and shy parameters are the shear factors in the x and y directions, respectively.

Implementing Rotation, Flip, and Shear

Let's develop the GeomManip class in a manner similar to what we did for pan and zoom. We'll build the controller class first and then the GUI class. Here are the two classes:

  1. GeomManip. This class implements the GeomManipController interface.

  2. ManipUI. This class implements the slider interfaces for adjusting the rotate and shear values.

Figure 7.13 shows the model-view-controller architecture for the rotation and shear features, which resembles the design for scroll and for zoom. Listing 7.16 shows the code for GeomManip.

FIGURE 7.13 The data flow for rotation and shear

LISTING 7.16 The GeomManip class

package com.vistech.imageviewer;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;

public class GeomManip implements GeomManipController {
  protected AffineTransform atx = new AffineTransform();
  // Rotation variables
  protected double rotationAngle = 0.0;
  protected boolean rotateOn = true;
  protected int rotationCenterX = 0;
  protected int rotationCenterY = 0;
  // Shear variables
  protected boolean shearOn = true;
  protected double shearFactor = 0.0;
  protected double shearX =0.0, shearY=0.0;
  protected ImageManipulator imageCanvas;
  protected int flipMode = 0;

  public GeomManip(){}
  public GeomManip(ImageManipulator imageCanvas){ this.imageCanvas = imageCanvas;}

  public void setImageManipulator(ImageManipulator imageCanvas){
   this.imageCanvas = imageCanvas;
  }

  public synchronized void setFlipMode(int mode){
   if(mode == flipMode) return;
   int oldmode = flipMode;
   flipMode = mode;
  }

  public int getFlipMode(){ return flipMode;}

  public void setShearFactor(double shearFactor){
   this.shearFactor = shearFactor;
   imageCanvas.setShearFactor(shearFactor);
  }
  public double getShearFactor(){ return shearFactor;}

  public double getShearFactorX(){ return shearX;}
  public double getShearFactorY(){return shearY;}

  public void setRotationAngle(double rotationAngle){
   this.rotationAngle = rotationAngle;
   imageCanvas.setRotationAngle(rotationAngle);
  }

  public double getRotationAngle(){ return rotationAngle;}

  public void rotate(double theta){
   double ang = this.rotationAngle -theta;
   Dimension dim = imageCanvas.getImageSize();
   int wid = dim.width;
   int ht = dim.height;
   setRotationAngle(theta);
   atx = imageCanvas.getTransform();
   atx.rotate(ang, wid/2, ht/2);
   imageCanvas.applyTransform(atx);
  }

  public void rotate(double theta, int rotCenterX, int rotCenterY){
   double ang = this.rotationAngle -theta;
   setRotationAngle(theta);
   atx = imageCanvas.getTransform();
   atx.rotate(ang, rotCenterX, rotCenterY);
   imageCanvas.applyTransform(atx);
  }

  public void resetAndRotate(double theta) {
   BufferedImage image = imageCanvas.getOffScreenImage();
   int wid = image.getWidth();
   int ht = image.getHeight();
   setRotationAngle(theta);
   atx.setToRotation(theta, wid/2, ht/2);
   imageCanvas.applyTransform(atx);
  }

  public void shear(double shx, double shy){
   double shxIncr = shearX -shx;
   double shyIncr = shearY -shy;
   setShearFactor(shx);
   this.shearX = shx;
   this.shearY = shy;
   atx = imageCanvas.getTransform();
   atx.shear(shxIncr, shyIncr);
   imageCanvas.applyTransform(atx);
  }

  public void shearIncr(double shxIncr, double shyIncr){
   shearX += shxIncr;
   shearY += shyIncr;
   setShearFactor(shearX);
   atx.shear(shxIncr, shyIncr);
   imageCanvas.applyTransform(atx);
  }

  public void resetAndShear(double shx, double shy){
   shearX =shx; shearY = shy;
   atx.setToShear(shx,shy);
   setShearFactor(shearX);
   imageCanvas.applyTransform(atx);
  }

  public static AffineTransform createFlipTransform(int mode,
                          int imageWid,
                          int imageHt){
    AffineTransform at = new AffineTransform();
    switch(mode){
      case FlipMode.NORMAL:
       break;
      case FlipMode.TOP_BOTTOM:
       at = new AffineTransform(new double[] {1.0,0.0,0.0,-1.0});
       at.translate(0.0, -imageHt);
       break;
      case FlipMode.LEFT_RIGHT :
       at = new AffineTransform(new double[] {-1.0,0.0,0.0,1.0});
       at.translate(-imageWid, 0.0);
       break;
      case FlipMode.TOP_BOTTOM_LEFT_RIGHT:
       at = new AffineTransform(new double[] {-1.0,0.0,0.0,-1.0});
       at.translate(-imageWid, -imageHt);
       break;
      default:
    }
    return at;
  }

  public void flip(int mode){
   Dimension dim = imageCanvas.getImageSize();
   int wid = dim.width;
   int ht = dim.height;
   AffineTransform flipTx = createFlipTransform(mode,wid,ht);
   atx = imageCanvas.getTransform();
   atx.concatenate(flipTx);
   imageCanvas.applyTransform(atx);
  }

  public void resetAndFlip(int mode){
   atx = new AffineTransform();
   flip(mode);
  }

  public void resetManipulation(){
   shearX = 0.0; shearY = 0.0;
   rotationAngle = 0.0;
   atx = new AffineTransform();
  }
}

Typically, images are rotated about their midpoint. In some situations, however, an image can be rotated around any arbitrary point. The rotate() methods in the GeomManip class meet both of these requirements.

The rotate(theta) method rotates the image about its midpoint, irrespective of where the image is positioned in the viewport. The input parameter theta is the angle of rotation from the original position of the image. When this method is called, the image might have been rotated already. This method therefore computes the difference between current rotation angle and the input. Then it gets the midpoint of the current image on the canvas. It then calls the rotate() method of the AffineTransform class with the difference in angles and the center point of the image as its inputs.

The rotate(theta, rotCenterX, rotCenterY) method rotates the image about any arbitrary point. The resetAndRotate() method implements absolute rotation about the midpoint. The setToRotation() method resets atx and rotates it by a fixed amount.

The shear methods are similar to the scale and rotate methods.

The AffineTransform class doesn't have an explicit flip transformation. We discussed how to implement flip in the preceding section and defined a method called createFlipTransform(). The flip() method uses createFlipTransform() to flip the image at any stage of image manipulation. Note that here we use the concatenate() method to concatenate the flip transformation to the current transformation atx. The resetAndFlip() method resets the current transformation and flips the image in the direction specified in the input.

User Interface for Rotation and Shear

Implementing rotation and shear is straightforward. We can directly use the transformation methods for rotation and shear in the GeomManip class. But first we need a GUI to operate on the GeomManip class. Figure 7.14 shows a screen shot of a panel that has two tabs: Rotate and Shear. To launch this panel, select the Rotate/Shear option in the Manipulate menu. You can either use the slider or enter a value in the text field. Notice that in the Rotate tab, the angles vary from –360 to +360, thereby enabling rotation in the clockwise or counterclockwise direction. When you move the slider, the text field reflects the slider's current value.

FIGURE 7.14 The Rotate and Shear panel

We'll provide only some code snippets because implementing the GUI involves a large chunk of code. Listing 7.17 shows the code for ManipUI.

LISTING 7.17 The ManipUI class

public class ManipUI extends JPanel{
  protected JTabbedPane jtp;
  protected int startValue = 0;
  protected int minValue = -360, maxValue = 360;
  protected JTextField rotateValueField;
  protected double rotateValue = 0.0;
  protected int rotateStartValue = 0;
  protected JSlider rotateSlider;

  protected int shearMinValue = -200;
  protected int shearMaxValue = 200;
  protected JTextField shearValueField;
  protected int shearValue = 0;
  protected int shearStartValue = 0;
  protected JSlider shearSlider;
  protected GeomManipController imageViewer;

  public ManipUI(GeomManipController manip) {
   imageViewer = manip;
   createUI();
  }

  private void createUI() {
   JPanel rpanel = createRotatePanel();
   JPanel spanel = createShearPanel();
   jtp = new JTabbedPane();
   jtp.addTab("Rotate", rpanel);
   jtp.addTab("Shear", spanel);
   add(jtp);
  }

  protected JPanel createRotatePanel() {
    JButton resetButton = new JButton("Reset Rotate");
    resetButton.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e){
         rotateSlider.setValue(rotateStartValue);
         rotateValueField.setText((new Double(rotateStartValue)).toString());
         imageViewer.rotate(0.0);
        }
      }
    );

    rotateValueField = new JTextField(5);
    rotateValueField.addActionListener(
      new ActionListener() {
       public void actionPerformed(ActionEvent e){
         try {
          String str = ((JTextField)e.getSource()).getText();
          rotateValue = (Double.valueOf(str)).doubleValue();

          rotateSlider.setValue((int)rotateValue);
          imageViewer.rotate(rotateValue*(Math.PI/180.0));
         } catch (Exception e1){}
       }
      }
    );

    rotateValueField.setText(Integer.toString(rotateStartValue));
    JLabel rotateLabel = new JLabel("Rotate");

    rotateSlider = new JSlider(minValue,maxValue,startValue);
    rotateSlider.setMajorTickSpacing(120);
    rotateSlider.setMinorTickSpacing(12);
    rotateSlider.setExtent(12);
    rotateSlider.setPaintTicks(true);
    rotateSlider.setPaintLabels(true);

    rotateSlider.addChangeListener(
      new ChangeListener() {
       public void stateChanged(ChangeEvent e){
         double rotateValueOld = rotateValue;
         rotateValue = ((JSlider)(e.getSource())).getValue();
         imageViewer.rotate(rotateValue*(Math.PI/180.0));
         rotateValueField.setText(Integer.toString((int)rotateValue));
       }
      }
    );

    JPanel rotatepan = new JPanel();
    // Grid layout
   return rotatepan;
  }

  protected JPanel createShearPanel() {

   // Code similar to createRotatePanel
  }

  public void resetManipulation(){
   shearSlider.setValue((int)(shearStartValue*100));
   shearValueField.setText(Double.toString(shearStartValue));
   rotateValueField.setText(Integer.toString((int)rotateStartValue));
   rotateSlider.setValue((int)rotateStartValue);
  }
}

Most of the code in Listing 7.17 is self-explanatory. The rotateSlider event–handling method calls the rotate() method with the current rotateSlider value. Likewise, the shearSlider event–handling method calls the shear() method with the current shearSlider value.

The code snippets that follow, which are from the ImageManip2D application, show how to use the GeomManip and ManipUI classes in an application:

ImageManipulator viewer = new ImageCanvas2D();
GeomManipController manip = new GeomManip(viewer);


 rot.addActionListener(
  new ActionListener() {
   public void actionPerformed(ActionEvent e){
     if(manipFrame == null) {
      manipFrame = new JFrame();
      ManipUI manipui = new ManipUI(manip);
      manipFrame.getContentPane().add(manipui);
      manipFrame.pack();
     }
     manipFrame.show();
   }
  }
 );

The rot parameter represents the Rotate/Shear option on the Manipulate menu. The code snippet is the event handler that launches the frame shown in Figure 7.14.

The screen shot in Figure 7.15 shows the image viewer when pan, zoom, rotate, and shear have all been performed. Besides the Lens and Rotate/Shear options, the Manipulate menu also has the option Flip.

FIGURE 7.15 Performing pan, zoom, flip, rotate, and shear together

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020