## Examples of java.awt.geom.AffineTransform

• java.awt.geom.AffineTransform
The `AffineTransform` class represents a 2D affine transform that performs a linear mapping from 2D coordinates to other 2D coordinates that preserves the "straightness" and "parallelness" of lines. Affine transformations can be constructed using sequences of translations, scales, flips, rotations, and shears.

Such a coordinate transformation can be represented by a 3 row by 3 column matrix with an implied last row of [ 0 0 1 ]. This matrix transforms source coordinates {@code (x,y)} intodestination coordinates {@code (x',y')} by consideringthem to be a column vector and multiplying the coordinate vector by the matrix according to the following process:

` [ x']   [  m00  m01  m02  ] [ x ]   [ m00x + m01y + m02 ] [ y'] = [  m10  m11  m12  ] [ y ] = [ m10x + m11y + m12 ] [ 1 ]   [   0    0    1   ] [ 1 ]   [         1         ] `

#### Handling 90-Degree Rotations

In some variations of the `rotate` methods in the `AffineTransform` class, a double-precision argument specifies the angle of rotation in radians. These methods have special handling for rotations of approximately 90 degrees (including multiples such as 180, 270, and 360 degrees), so that the common case of quadrant rotation is handled more efficiently. This special handling can cause angles very close to multiples of 90 degrees to be treated as if they were exact multiples of 90 degrees. For small multiples of 90 degrees the range of angles treated as a quadrant rotation is approximately 0.00000121 degrees wide. This section explains why such special care is needed and how it is implemented.

Since 90 degrees is represented as `PI/2` in radians, and since PI is a transcendental (and therefore irrational) number, it is not possible to exactly represent a multiple of 90 degrees as an exact double precision value measured in radians. As a result it is theoretically impossible to describe quadrant rotations (90, 180, 270 or 360 degrees) using these values. Double precision floating point values can get very close to non-zero multiples of `PI/2` but never close enough for the sine or cosine to be exactly 0.0, 1.0 or -1.0. The implementations of `Math.sin()` and `Math.cos()` correspondingly never return 0.0 for any case other than `Math.sin(0.0)`. These same implementations do, however, return exactly 1.0 and -1.0 for some range of numbers around each multiple of 90 degrees since the correct answer is so close to 1.0 or -1.0 that the double precision significand cannot represent the difference as accurately as it can for numbers that are near 0.0.

The net result of these issues is that if the `Math.sin()` and `Math.cos()` methods are used to directly generate the values for the matrix modifications during these radian-based rotation operations then the resulting transform is never strictly classifiable as a quadrant rotation even for a simple case like `rotate(Math.PI/2.0)`, due to minor variations in the matrix caused by the non-0.0 values obtained for the sine and cosine. If these transforms are not classified as quadrant rotations then subsequent code which attempts to optimize further operations based upon the type of the transform will be relegated to its most general implementation.

Because quadrant rotations are fairly common, this class should handle these cases reasonably quickly, both in applying the rotations to the transform and in applying the resulting transform to the coordinates. To facilitate this optimal handling, the methods which take an angle of rotation measured in radians attempt to detect angles that are intended to be quadrant rotations and treat them as such. These methods therefore treat an angle theta as a quadrant rotation if either `Math.sin(theta)` or `Math.cos(theta)` returns exactly 1.0 or -1.0. As a rule of thumb, this property holds true for a range of approximately 0.0000000211 radians (or 0.00000121 degrees) around small multiples of `Math.PI/2.0`. @version 1.77, 03/09/06 @author Jim Graham @since 1.2

 `149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183` ```    int width = old_img.getWidth();     int height = old_img.getHeight();     BufferedImage new_img = new BufferedImage(height,width,BufferedImage.TYPE_INT_RGB);                Graphics2D g2d =new_img.createGraphics();                 AffineTransform origXform = g2d.getTransform();         AffineTransform newXform = (AffineTransform)(origXform.clone());         // center of rotation is center of the panel     double radian = 0;         double xRot = 0;         double yRot = 0;     switch(orient){     case 3:       radian = 180.0;       xRot = width/2.0;       yRot = height/2.0;     case 6:       radian = 90.0;           xRot = height/2.0;           yRot = xRot;       break;     case 8:       radian = 270.0;           xRot = width/2.0;           yRot = xRot;           break;         default:           return false;     }         newXform.rotate(Math.toRadians(radian), xRot, yRot);         g2d.setTransform(newXform);           // draw image centered in panel         g2d.drawImage(old_img, 0, 0, null);         // Reset to Original ```
View Full Code Here

 `565758596061626364656667686970` ```    int height = old_img.getHeight();         BufferedImage new_img = new BufferedImage(height,width,BufferedImage.TYPE_INT_BGR);                Graphics2D g2d =new_img.createGraphics();                 AffineTransform origXform = g2d.getTransform();         AffineTransform newXform = (AffineTransform)(origXform.clone());         // center of rotation is center of the panel         double xRot = width/2.0;         newXform.rotate(Math.toRadians(270.0), xRot, xRot);         g2d.setTransform(newXform);           // draw image centered in panel         g2d.drawImage(old_img, 0, 0, null);         // Reset to Original ```
View Full Code Here

 `461462463464465466467468469470471` ```        g2d.setRenderingHint(RenderingHints.KEY_RENDERING,             smooth ? RenderingHints.VALUE_RENDER_QUALITY :                 RenderingHints.VALUE_RENDER_SPEED         );         AffineTransform at = AffineTransform.getScaleInstance(             (double) w / width,             (double) h / height         );         g2d.drawImage(image, at, null);         g2d.dispose(); ```
View Full Code Here

 `151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210` ```        if (log.isDebugEnabled()) {             log.debug("Generating SVG at " + deviceResolution + "dpi.");         }         final float uaResolution = userAgent.getSourceResolution();         SVGUserAgent ua = new SVGUserAgent(userAgent, new AffineTransform());         //Scale for higher resolution on-the-fly images from Batik         double s = uaResolution / deviceResolution;         AffineTransform resolutionScaling = new AffineTransform();         resolutionScaling.scale(s, s);         //Controls whether text painted by Batik is generated using text or path operations         boolean strokeText = false;         Configuration cfg = pdfInfo.cfg;         if (cfg != null) {             strokeText = cfg.getChild("stroke-text", true).getValueAsBoolean(strokeText);         }         BridgeContext ctx = new PDFBridgeContext(ua,                 (strokeText ? null : pdfInfo.fi),                 userAgent.getFactory().getImageManager(),                 userAgent.getImageSessionContext(),                 new AffineTransform());         //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine)         //to it.         Document clonedDoc = BatikUtil.cloneSVGDocument(doc);         GraphicsNode root;         try {             GVTBuilder builder = new GVTBuilder();             root = builder.build(ctx, clonedDoc);         } catch (Exception e) {             SVGEventProducer eventProducer = SVGEventProducer.Provider.get(                     context.getUserAgent().getEventBroadcaster());             eventProducer.svgNotBuilt(this, e, getDocumentURI(doc));             return;         }         // get the 'width' and 'height' attributes of the SVG document         float w = (float)ctx.getDocumentSize().getWidth() * 1000f;         float h = (float)ctx.getDocumentSize().getHeight() * 1000f;         float sx = pdfInfo.width / w;         float sy = pdfInfo.height / h;         //Scaling and translation for the bounding box of the image         AffineTransform scaling = new AffineTransform(                 sx, 0, 0, sy, xOffset / 1000f, yOffset / 1000f);         //Transformation matrix that establishes the local coordinate system for the SVG graphic         //in relation to the current coordinate system         AffineTransform imageTransform = new AffineTransform();         imageTransform.concatenate(scaling);         imageTransform.concatenate(resolutionScaling);         /*          * Clip to the svg area.          * Note: To have the svg overlay (under) a text area then use          * an fo:block-container ```
View Full Code Here

 `729730731732733734735736737738739` ```      Graphics2D g2 = iconImage.createGraphics();       g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,           RenderingHints.VALUE_INTERPOLATION_BICUBIC);       g2.setRenderingHint(RenderingHints.KEY_RENDERING,           RenderingHints.VALUE_RENDER_QUALITY);       AffineTransform z = g2.getTransform();       g2.setTransform(z);       icon.paintIcon(null, g2, 0, 0);       g2.dispose();       BufferedImage scaled = scaleDown(iconImage, width, height);       // Return new Icon ```
View Full Code Here

 `168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198` ```    int height = old_img.getHeight();         BufferedImage new_img = new BufferedImage(height,width,BufferedImage.TYPE_INT_RGB);                Graphics2D g2d =new_img.createGraphics();                 AffineTransform origXform = g2d.getTransform();         AffineTransform newXform = (AffineTransform)(origXform.clone());         // center of rotation is center of the panel         double xRot = 0;         double yRot = 0;     switch(orient){     case 3:       xRot = width/2.0;       yRot = height/2.0;     case 6:           xRot = height/2.0;           yRot = xRot;       break;     case 8:           xRot = width/2.0;           yRot = xRot;           break;         default:           return false;     }         newXform.rotate(Math.toRadians(radian), xRot, yRot);         g2d.setTransform(newXform);           // draw image centered in panel         g2d.drawImage(old_img, 0, 0, null);         // Reset to Original ```
View Full Code Here

 `155156157158159160161162163164165` ```        _currentPage = currentPage;         _pageHeight = height;                 _currentPage.saveState();                 _transform = new AffineTransform();         _transform.scale(1.0d / _dotsPerPoint, 1.0d / _dotsPerPoint);                 _stroke = transformStroke(STROKE_ONE);         _originalStroke = _stroke;         _oldStroke = _stroke; ```
View Full Code Here

 `448449450451452453454455456457458459460` ```        _font = ((ITextFSFont)font);     }         private AffineTransform normalizeMatrix(AffineTransform current) {         double[] mx = new double[6];         AffineTransform result = new AffineTransform();         result.getMatrix(mx);         mx[3] = -1;         mx[5] = _pageHeight;         result = new AffineTransform(mx);         result.concatenate(current);         return result;     } ```
View Full Code Here

 `462463464465466467468469470471472473474475` ```    public void drawString(String s, float x, float y, JustificationInfo info) {         if (s.length() == 0)             return;         PdfContentByte cb = _currentPage;         ensureFillColor();         AffineTransform at = (AffineTransform)getTransform().clone();         at.translate(x, y);         AffineTransform inverse = normalizeMatrix(at);         AffineTransform flipper = AffineTransform.getScaleInstance(1, -1);         inverse.concatenate(flipper);         inverse.scale(_dotsPerPoint, _dotsPerPoint);         double[] mx = new double[6];         inverse.getMatrix(mx);         cb.beginText(); ```
View Full Code Here

 `760761762763764765766767768769770771772773774775` ```                        if (fsImage.getHeight() <= 0 || fsImage.getWidth() <= 0) {                 return;             }                         AffineTransform at = AffineTransform.getTranslateInstance(x,y);             at.translate(0, fsImage.getHeight());             at.scale(fsImage.getWidth(), fsImage.getHeight());                         AffineTransform inverse = normalizeMatrix(_transform);             AffineTransform flipper = AffineTransform.getScaleInstance(1,-1);             inverse.concatenate(at);             inverse.concatenate(flipper);                         double[] mx = new double[6];             inverse.getMatrix(mx); ```
View Full Code Here