Example usage for java.awt.geom AffineTransform createTransformedShape

List of usage examples for java.awt.geom AffineTransform createTransformedShape

Introduction

In this page you can find the example usage for java.awt.geom AffineTransform createTransformedShape.

Prototype

public Shape createTransformedShape(Shape pSrc) 

Source Link

Document

Returns a new Shape object defined by the geometry of the specified Shape after it has been transformed by this transform.

Usage

From source file:org.apache.fop.render.pdf.PDFDocumentHandler.java

private Rectangle2D toPDFCoordSystem(Rectangle box, AffineTransform transform) {
    return transform.createTransformedShape(box).getBounds2D();
}

From source file:org.apache.pdfbox.rendering.PageDrawer.java

/**
 * Render the font using the Glyph2D interface.
 * //from   w w w  . j a va2 s. c om
 * @param glyph2D the Glyph2D implementation provided a GeneralPath for each glyph
 * @param font the font
 * @param code character code
 * @param displacement the glyph's displacement (advance)
 * @param at the transformation
 * @throws IOException if something went wrong
 */
private void drawGlyph2D(Glyph2D glyph2D, PDFont font, int code, Vector displacement, AffineTransform at)
        throws IOException {
    PDGraphicsState state = getGraphicsState();
    RenderingMode renderingMode = state.getTextState().getRenderingMode();

    GeneralPath path = glyph2D.getPathForCharacterCode(code);
    if (path != null) {
        // stretch non-embedded glyph if it does not match the width contained in the PDF
        if (!font.isEmbedded()) {
            float fontWidth = font.getWidthFromFont(code);
            if (fontWidth > 0 && // ignore spaces
                    Math.abs(fontWidth - displacement.getX() * 1000) > 0.0001) {
                float pdfWidth = displacement.getX() * 1000;
                at.scale(pdfWidth / fontWidth, 1);
            }
        }

        // render glyph
        Shape glyph = at.createTransformedShape(path);

        if (renderingMode.isFill()) {
            graphics.setComposite(state.getNonStrokingJavaComposite());
            graphics.setPaint(getNonStrokingPaint());
            setClip();
            graphics.fill(glyph);
        }

        if (renderingMode.isStroke()) {
            graphics.setComposite(state.getStrokingJavaComposite());
            graphics.setPaint(getStrokingPaint());
            graphics.setStroke(getStroke());
            setClip();
            graphics.draw(glyph);
        }

        if (renderingMode.isClip()) {
            textClippingArea.add(new Area(glyph));
        }
    }
}

From source file:org.apache.pdfbox.rendering.PageDrawer.java

private void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException {
    graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
    setClip();//  w ww .j a  v  a2  s  .  com
    PDSoftMask softMask = getGraphicsState().getSoftMask();
    if (softMask != null) {
        AffineTransform imageTransform = new AffineTransform(at);
        imageTransform.scale(1, -1);
        imageTransform.translate(0, -1);
        Paint awtPaint = new TexturePaint(image, new Rectangle2D.Double(imageTransform.getTranslateX(),
                imageTransform.getTranslateY(), imageTransform.getScaleX(), imageTransform.getScaleY()));
        awtPaint = applySoftMaskToPaint(awtPaint, softMask);
        graphics.setPaint(awtPaint);
        Rectangle2D unitRect = new Rectangle2D.Float(0, 0, 1, 1);
        graphics.fill(at.createTransformedShape(unitRect));
    } else {
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        AffineTransform imageTransform = new AffineTransform(at);
        imageTransform.scale(1.0 / width, -1.0 / height);
        imageTransform.translate(0, -height);
        graphics.drawImage(image, imageTransform, null);
    }
}

From source file:org.csstudio.utility.batik.SVGHandler.java

private Shape calculateShape() {
    double width = originalDimension.getWidth();
    double height = originalDimension.getHeight();

    double[] flatmatrix = new double[] { matrix[0][0], matrix[1][0], matrix[0][1], matrix[1][1] };
    AffineTransform at = new AffineTransform(flatmatrix);
    Shape curAOI = new Rectangle2D.Double(0, 0, width, height);
    return at.createTransformedShape(curAOI);
}

From source file:org.dwfa.ace.graph.AceGraphRenderer.java

/**
 * Draws the edge <code>e</code>, whose endpoints are at
 * <code>(x1,y1)</code> and <code>(x2,y2)</code>, on the graphics context
 * <code>g</code>./*from w  w w  . j  a v a2  s  .co  m*/
 * The <code>Shape</code> provided by the <code>EdgeShapeFunction</code>
 * instance
 * is scaled in the x-direction so that its width is equal to the distance
 * between <code>(x1,y1)</code> and <code>(x2,y2)</code>.
 */
protected void drawSimpleEdge(Graphics2D g, Edge e, int x1, int y1, int x2, int y2) {
    Pair endpoints = e.getEndpoints();
    Vertex v1 = (Vertex) endpoints.getFirst();
    Vertex v2 = (Vertex) endpoints.getSecond();
    boolean isLoop = v1.equals(v2);
    Shape s2 = vertexShapeFunction.getShape(v2);
    Shape edgeShape = edgeShapeFunction.getShape(e);

    boolean edgeHit = true;
    boolean arrowHit = true;
    Rectangle deviceRectangle = null;
    if (screenDevice != null) {
        Dimension d = screenDevice.getSize();
        if (d.width <= 0 || d.height <= 0) {
            d = screenDevice.getPreferredSize();
        }
        deviceRectangle = new Rectangle(0, 0, d.width, d.height);
    }

    AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1);

    if (isLoop) {
        // this is a self-loop. scale it is larger than the vertex
        // it decorates and translate it so that its nadir is
        // at the center of the vertex.
        Rectangle2D s2Bounds = s2.getBounds2D();
        xform.scale(s2Bounds.getWidth(), s2Bounds.getHeight());
        xform.translate(0, -edgeShape.getBounds2D().getWidth() / 2);
    } else {
        // this is a normal edge. Rotate it to the angle between
        // vertex endpoints, then scale it to the distance between
        // the vertices
        float dx = x2 - x1;
        float dy = y2 - y1;
        float thetaRadians = (float) Math.atan2(dy, dx);
        xform.rotate(thetaRadians);
        float dist = (float) Math.sqrt(dx * dx + dy * dy);
        xform.scale(dist, 1.0);
    }

    edgeShape = xform.createTransformedShape(edgeShape);

    if (deviceRectangle == null) {
        edgeHit = false;
    } else {
        edgeHit = viewTransformer.transform(edgeShape).intersects(deviceRectangle);
    }

    if (edgeHit == true) {

        Paint oldPaint = g.getPaint();

        // get Paints for filling and drawing
        // (filling is done first so that drawing and label use same Paint)
        Paint fill_paint = edgePaintFunction.getFillPaint(e);
        if (fill_paint != null) {
            g.setPaint(fill_paint);
            g.fill(edgeShape);
        }
        Paint draw_paint = edgePaintFunction.getDrawPaint(e);
        if (draw_paint != null) {
            g.setPaint(draw_paint);
            g.draw(edgeShape);
        }

        float scalex = (float) g.getTransform().getScaleX();
        float scaley = (float) g.getTransform().getScaleY();
        // see if arrows are too small to bother drawing
        if (scalex < .3 || scaley < .3)
            return;

        if (edgeArrowPredicate.evaluate(e)) {

            Shape destVertexShape = vertexShapeFunction.getShape((Vertex) e.getEndpoints().getSecond());
            AffineTransform xf = AffineTransform.getTranslateInstance(x2, y2);
            destVertexShape = xf.createTransformedShape(destVertexShape);

            arrowHit = viewTransformer.transform(destVertexShape).intersects(deviceRectangle);
            if (arrowHit) {

                AffineTransform at;
                if (edgeShape instanceof GeneralPath)
                    at = getArrowTransform((GeneralPath) edgeShape, destVertexShape);
                else
                    at = getArrowTransform(new GeneralPath(edgeShape), destVertexShape);
                if (at == null)
                    return;
                Shape arrow = edgeArrowFunction.getArrow(e);
                arrow = at.createTransformedShape(arrow);
                // note that arrows implicitly use the edge's draw paint
                g.fill(arrow);
            }
            if (e instanceof UndirectedEdge) {
                Shape vertexShape = vertexShapeFunction.getShape((Vertex) e.getEndpoints().getFirst());
                xf = AffineTransform.getTranslateInstance(x1, y1);
                vertexShape = xf.createTransformedShape(vertexShape);

                arrowHit = viewTransformer.transform(vertexShape).intersects(deviceRectangle);

                if (arrowHit) {
                    AffineTransform at;
                    if (edgeShape instanceof GeneralPath)
                        at = getReverseArrowTransform((GeneralPath) edgeShape, vertexShape, !isLoop);
                    else
                        at = getReverseArrowTransform(new GeneralPath(edgeShape), vertexShape, !isLoop);
                    if (at == null)
                        return;
                    Shape arrow = edgeArrowFunction.getArrow(e);
                    arrow = at.createTransformedShape(arrow);
                    g.fill(arrow);
                }
            }
        }
        // use existing paint for text if no draw paint specified
        if (draw_paint == null)
            g.setPaint(oldPaint);
        String label = edgeStringer.getLabel(e);
        if (label != null) {
            labelEdge(g, e, label, x1, x2, y1, y2);
        }

        // restore old paint
        g.setPaint(oldPaint);
    }
}

From source file:org.dwfa.ace.graph.AceGraphRenderer.java

/**
 * Paints the vertex <code>v</code> at the location <code>(x,y)</code> on
 * the graphics context <code>g_gen</code>. The vertex is painted
 * using the shape returned by this instance's
 * <code>VertexShapeFunction</code>,
 * and the foreground and background (border) colors provided by this
 * instance's <code>VertexColorFunction</code>. Delegates drawing the
 * label (if any) for this vertex to <code>labelVertex</code>.
 */// w ww.  ja  va2 s  .  c o  m
public void paintVertex(Graphics g, Vertex v, int x, int y) {
    if (!vertexIncludePredicate.evaluate(v))
        return;

    boolean vertexHit = true;
    Rectangle deviceRectangle = null;
    Graphics2D g2d = (Graphics2D) g;
    if (screenDevice != null) {
        Dimension d = screenDevice.getSize();
        if (d.width <= 0 || d.height <= 0) {
            d = screenDevice.getPreferredSize();
        }
        deviceRectangle = new Rectangle(0, 0, d.width, d.height);
    }

    Stroke old_stroke = g2d.getStroke();
    Stroke new_stroke = vertexStrokeFunction.getStroke(v);
    if (new_stroke != null) {
        g2d.setStroke(new_stroke);
    }
    // get the shape to be rendered
    Shape s = vertexShapeFunction.getShape(v);

    // create a transform that translates to the location of
    // the vertex to be rendered
    AffineTransform xform = AffineTransform.getTranslateInstance(x, y);
    // transform the vertex shape with xtransform
    s = xform.createTransformedShape(s);

    if (deviceRectangle == null) {
        vertexHit = false;
    } else {
        vertexHit = viewTransformer.transform(s).intersects(deviceRectangle);
    }

    if (vertexHit) {

        if (vertexShapeRendered) {
            if (vertexIconFunction != null) {
                paintIconForVertex(g2d, v, x, y);
            } else {
                paintShapeForVertex(g2d, v, s);
            }
        }

        if (new_stroke != null) {
            g2d.setStroke(old_stroke);
        }
        String label = vertexStringer.getLabel(v);
        if (label != null) {
            labelVertex(g, v, label, x, y);
        }
    }
}

From source file:org.fao.geonet.services.region.GetMap.java

public Element exec(Element params, ServiceContext context) throws Exception {
    Util.toLowerCase(params);/*ww w  .  j  a  v  a  2  s.c om*/
    String id = params.getChildText(Params.ID);
    String srs = Util.getParam(params, MAP_SRS_PARAM, "EPSG:4326");
    String widthString = Util.getParamText(params, WIDTH_PARAM);
    String heightString = Util.getParamText(params, HEIGHT_PARAM);
    String background = Util.getParamText(params, BACKGROUND_PARAM);
    String geomParam = Util.getParamText(params, GEOM_PARAM);
    String geomType = Util.getParam(params, GEOM_TYPE_PARAM, GeomFormat.WKT.toString());
    String geomSrs = Util.getParam(params, GEOM_SRS_PARAM, "EPSG:4326");

    if (id == null && geomParam == null) {
        throw new BadParameterEx(Params.ID, "Either " + GEOM_PARAM + " or " + Params.ID + " is required");
    }
    if (id != null && geomParam != null) {
        throw new BadParameterEx(Params.ID, "Only one of " + GEOM_PARAM + " or " + Params.ID + " is permitted");
    }

    // see calculateImageSize for more parameter checks

    Geometry geom = null;
    if (id != null) {
        Collection<RegionsDAO> daos = context.getApplicationContext().getBeansOfType(RegionsDAO.class).values();
        for (RegionsDAO regionsDAO : daos) {
            geom = regionsDAO.getGeom(context, id, false, srs);
            if (geom != null) {
                break;
            }
        }
        if (geom == null) {
            throw new RegionNotFoundEx(id);
        }
    } else {
        GeomFormat format = GeomFormat.find(geomType);
        geom = format.parse(geomParam);
        if (!geomSrs.equals(srs)) {
            CoordinateReferenceSystem mapCRS = Region.decodeCRS(srs);
            CoordinateReferenceSystem geomCRS = Region.decodeCRS(geomSrs);
            MathTransform transform = CRS.findMathTransform(geomCRS, mapCRS, true);
            geom = JTS.transform(geom, transform);
        }
    }
    BufferedImage image;
    Envelope bboxOfImage = new Envelope(geom.getEnvelopeInternal());
    double expandFactor = 0.2;
    bboxOfImage.expandBy(bboxOfImage.getWidth() * expandFactor, bboxOfImage.getHeight() * expandFactor);
    Dimension imageDimenions = calculateImageSize(bboxOfImage, widthString, heightString);

    Exception error = null;
    if (background != null) {

        if (this.namedBackgrounds.containsKey(background)) {
            background = this.namedBackgrounds.get(background);
        }

        String minx = Double.toString(bboxOfImage.getMinX());
        String maxx = Double.toString(bboxOfImage.getMaxX());
        String miny = Double.toString(bboxOfImage.getMinY());
        String maxy = Double.toString(bboxOfImage.getMaxY());
        background = background.replace("{minx}", minx).replace("{maxx}", maxx).replace("{miny}", miny)
                .replace("{maxy}", maxy).replace("{srs}", srs)
                .replace("{width}", Integer.toString(imageDimenions.width))
                .replace("{height}", Integer.toString(imageDimenions.height)).replace("{MINX}", minx)
                .replace("{MAXX}", maxx).replace("{MINY}", miny).replace("{MAXY}", maxy).replace("{SRS}", srs)
                .replace("{WIDTH}", Integer.toString(imageDimenions.width))
                .replace("{HEIGHT}", Integer.toString(imageDimenions.height));

        InputStream in = null;
        try {
            URL imageUrl = new URL(background);
            in = imageUrl.openStream();
            image = ImageIO.read(in);
        } catch (IOException e) {
            image = new BufferedImage(imageDimenions.width, imageDimenions.height, BufferedImage.TYPE_INT_ARGB);
            error = e;
        } finally {
            if (in != null) {
                IOUtils.closeQuietly(in);
            }

        }
    } else {
        image = new BufferedImage(imageDimenions.width, imageDimenions.height, BufferedImage.TYPE_INT_ARGB);
    }

    Graphics2D graphics = image.createGraphics();
    try {
        if (error != null) {
            graphics.drawString(error.getMessage(), 0, imageDimenions.height / 2);
        }
        ShapeWriter shapeWriter = new ShapeWriter();
        AffineTransform worldToScreenTransform = worldToScreenTransform(bboxOfImage, imageDimenions);
        //            MathTransform mathTransform = new AffineTransform2D(worldToScreenTransform);
        //            Geometry screenGeom = JTS.transform(geom, mathTransform);
        Shape shape = worldToScreenTransform.createTransformedShape(shapeWriter.toShape(geom));
        graphics.setColor(Color.yellow);
        graphics.draw(shape);

        graphics.setColor(new Color(255, 255, 0, 100));
        graphics.fill(shape);

    } finally {
        graphics.dispose();
    }

    File tmpFile = File.createTempFile("GetMap", "." + format);
    ImageIO.write(image, format, tmpFile);
    return BinaryFile.encode(200, tmpFile.getAbsolutePath(), true);
}

From source file:org.nuxeo.pdf.service.PDFTransformationServiceImpl.java

public Point2D computeTranslationVector(double pageWidth, double watermarkWidth, double pageHeight,
        double watermarkHeight, WatermarkProperties properties) {
    double xTranslation;
    double yTranslation;
    double xRotationOffset = 0;
    double yRotationOffset = 0;

    if (properties.getTextRotation() != 0) {
        Rectangle2D rectangle2D = new Rectangle2D.Double(0, -watermarkHeight, watermarkWidth, watermarkHeight);
        AffineTransform at = AffineTransform.getRotateInstance(-Math.toRadians(properties.getTextRotation()), 0,
                0);/*from w ww . j a v  a 2 s  . c o  m*/
        Shape shape = at.createTransformedShape(rectangle2D);
        Rectangle2D rotated = shape.getBounds2D();

        watermarkWidth = rotated.getWidth();
        if (!properties.isInvertX() || properties.isRelativeCoordinates()) {
            xRotationOffset = -rotated.getX();
        } else {
            xRotationOffset = rotated.getX();
        }

        watermarkHeight = rotated.getHeight();
        if (!properties.isInvertY() || properties.isRelativeCoordinates()) {
            yRotationOffset = rotated.getY() + rotated.getHeight();
        } else {
            yRotationOffset = -(rotated.getY() + rotated.getHeight());
        }

    }

    if (properties.isRelativeCoordinates()) {
        xTranslation = (pageWidth - watermarkWidth) * properties.getxPosition() + xRotationOffset;
        yTranslation = (pageHeight - watermarkHeight) * properties.getyPosition() + yRotationOffset;
    } else {
        xTranslation = properties.getxPosition() + xRotationOffset;
        yTranslation = properties.getyPosition() + yRotationOffset;
        if (properties.isInvertX())
            xTranslation = pageWidth - watermarkWidth - xTranslation;
        if (properties.isInvertY())
            yTranslation = pageHeight - watermarkHeight - yTranslation;
    }
    return new Point2D.Double(xTranslation, yTranslation);
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java

private void setPaint(final boolean invert, final double xoffset, final double yoffset, final boolean fill) {
    if (paint instanceof Color) {
        final Color color = (Color) paint;
        final int alpha = color.getAlpha();
        if (fill) {
            if (alpha != currentFillGState) {
                currentFillGState = alpha;
                PdfGState gs = fillGState[alpha];
                if (gs == null) {
                    gs = new PdfGState();
                    gs.setFillOpacity(alpha / 255.00f);
                    fillGState[alpha] = gs;
                }/*from  w w  w. j  a v a 2  s . c o m*/
                cb.setGState(gs);
            }
            cb.setColorFill(color);
        } else {
            if (alpha != currentStrokeGState) {
                currentStrokeGState = alpha;
                PdfGState gs = strokeGState[alpha];
                if (gs == null) {
                    gs = new PdfGState();
                    gs.setStrokeOpacity(alpha / 255.0f);
                    strokeGState[alpha] = gs;
                }
                cb.setGState(gs);
            }
            cb.setColorStroke(color);
        }
    } else if (paint instanceof GradientPaint) {
        final GradientPaint gp = (GradientPaint) paint;
        final Point2D p1 = gp.getPoint1();
        transform.transform(p1, p1);
        final Point2D p2 = gp.getPoint2();
        transform.transform(p2, p2);
        final Color c1 = gp.getColor1();
        final Color c2 = gp.getColor2();
        final PdfShading shading = PdfShading.simpleAxial(cb.getPdfWriter(), (float) p1.getX(),
                normalizeY((float) p1.getY()), (float) p2.getX(), normalizeY((float) p2.getY()), c1, c2);
        final PdfShadingPattern pat = new PdfShadingPattern(shading);
        if (fill) {
            cb.setShadingFill(pat);
        } else {
            cb.setShadingStroke(pat);
        }
    } else if (paint instanceof TexturePaint) {
        try {
            final TexturePaint tp = (TexturePaint) paint;
            final BufferedImage img = tp.getImage();
            final Rectangle2D rect = tp.getAnchorRect();
            final com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(img, null);
            final PdfPatternPainter pattern = cb.createPattern(image.getWidth(), image.getHeight());
            final AffineTransform inverse = this.normalizeMatrix();
            inverse.translate(rect.getX(), rect.getY());
            inverse.scale(rect.getWidth() / image.getWidth(), -rect.getHeight() / image.getHeight());
            final double[] mx = new double[6];
            inverse.getMatrix(mx);
            pattern.setPatternMatrix((float) mx[0], (float) mx[1], (float) mx[2], (float) mx[3], (float) mx[4],
                    (float) mx[5]);
            image.setAbsolutePosition(0, 0);
            pattern.addImage(image);
            if (fill) {
                cb.setPatternFill(pattern);
            } else {
                cb.setPatternStroke(pattern);
            }

        } catch (Exception ex) {
            if (fill) {
                cb.setColorFill(Color.gray);
            } else {
                cb.setColorStroke(Color.gray);
            }
        }
    } else {
        try {
            int type = BufferedImage.TYPE_4BYTE_ABGR;
            if (paint.getTransparency() == Transparency.OPAQUE) {
                type = BufferedImage.TYPE_3BYTE_BGR;
            }
            final BufferedImage img = new BufferedImage((int) width, (int) height, type);
            final Graphics2D g = (Graphics2D) img.getGraphics();
            g.transform(transform);
            final AffineTransform inv = transform.createInverse();
            Shape fillRect = new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight());
            fillRect = inv.createTransformedShape(fillRect);
            g.setPaint(paint);
            g.fill(fillRect);
            if (invert) {
                final AffineTransform tx = new AffineTransform();
                tx.scale(1, -1);
                tx.translate(-xoffset, -yoffset);
                g.drawImage(img, tx, null);
            }
            g.dispose();
            // g = null;
            final com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(img, null);
            final PdfPatternPainter pattern = cb.createPattern(width, height);
            image.setAbsolutePosition(0, 0);
            pattern.addImage(image);
            if (fill) {
                cb.setPatternFill(pattern);
            } else {
                cb.setPatternStroke(pattern);
            }
        } catch (Exception ex) {
            if (fill) {
                cb.setColorFill(Color.gray);
            } else {
                cb.setColorStroke(Color.gray);
            }
        }
    }
}

From source file:org.rhwlab.dispim.nucleus.NucleusData.java

public Shape getShape(long slice, int dim, int bufW, int bufH) {

    //System.out.printf("Ellipsoid center = (%d,%d,%d)\n",this.xC,this.yC,this.zC);
    Ellipse2d e;//from ww  w .j av a  2 s.  co  m
    switch (dim) {
    case 0:
        e = xPlaneEllipse((double) slice);
        break;
    case 1:
        e = yPlaneEllipse((double) slice);
        break;
    default:
        e = zPlaneEllipse((double) slice);
        break;
    }
    if (e != null) {
        //System.out.printf("%s dim=%d  slice=%d\n",this.getName(),dim,slice);
        AffineTransform toOrigin = AffineTransform.getTranslateInstance(-e.x, -e.y);
        AffineTransform back = AffineTransform.getTranslateInstance(e.x, e.y);
        AffineTransform xform = AffineTransform.getRotateInstance(e.cosine, e.sine);
        int scrX = SingleSlicePanel.screenX(e.low, dim, bufW);
        int scrY = SingleSlicePanel.screenY(e.low, dim, bufH);
        int scrHighX = SingleSlicePanel.screenX(e.high, dim, bufW);
        int scrHighY = SingleSlicePanel.screenY(e.high, dim, bufH);
        Shape shape = new Ellipse2D.Double(scrX, scrY, scrHighX - scrX, scrHighY - scrY);
        shape = toOrigin.createTransformedShape(shape);
        shape = xform.createTransformedShape(shape);
        shape = back.createTransformedShape(shape);
        //System.out.printf("e.a:%f e.b:%f e.x:%f e.y:%f\n",e.a,e.b,e.x,e.y);
        return shape;
    }
    return null;
}