Example usage for java.awt.geom AffineTransform translate

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

Introduction

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

Prototype

public void translate(double tx, double ty) 

Source Link

Document

Concatenates this transform with a translation transformation.

Usage

From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxImageHandler.java

public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException {
    assert context instanceof PDFRenderingContext;
    PDFRenderingContext pdfContext = (PDFRenderingContext) context;
    PDFContentGenerator generator = pdfContext.getGenerator();
    assert image instanceof ImagePDF;
    ImagePDF pdfImage = (ImagePDF) image;

    float x = (float) pos.getX() / 1000f;
    float y = (float) pos.getY() / 1000f;
    //        float w = (float)pos.getWidth() / 1000f;
    float h = (float) pos.getHeight() / 1000f;

    AffineTransform pageAdjust = new AffineTransform();
    AffineTransform at = generator.getAffineTransform();
    if (at != null) {
        pageAdjust.setToTranslation((float) (generator.getState().getTransform().getTranslateX()),
                (float) (generator.getState().getTransform().getTranslateY() - h - y));
    }/*from www  .ja  v  a2s. co  m*/
    FontInfo fontinfo = (FontInfo) context.getHint("fontinfo");
    String stream = createStreamForPDF(pdfImage, pdfContext.getPage(), pdfContext.getUserAgent(), pageAdjust,
            fontinfo, pos, pdfContext.getPageNumbers(), pdfContext.getPdfLogicalStructureHandler(),
            pdfContext.getCurrentSessionStructElem());

    if (stream == null) {
        return;
    }
    if (pageAdjust.getScaleX() != 0) {
        pageAdjust.translate(x * (1 / pageAdjust.getScaleX()), -y * (1 / -pageAdjust.getScaleY()));
    }
    generator.placeImage(pageAdjust, stream);
}

From source file:org.apache.fop.render.ps.PSSVGHandler.java

/**
 * Render the svg document./*from  w w  w  . j  a v a 2s .  co  m*/
 * @param context the renderer context
 * @param doc the svg document
 */
protected void renderSVGDocument(RendererContext context, Document doc) {
    PSInfo psInfo = getPSInfo(context);
    int xOffset = psInfo.currentXPosition;
    int yOffset = psInfo.currentYPosition;
    PSGenerator gen = psInfo.psGenerator;

    boolean paintAsBitmap = false;
    if (context != null) {
        Map foreign = (Map) context.getProperty(RendererContextConstants.FOREIGN_ATTRIBUTES);
        paintAsBitmap = ImageHandlerUtil.isConversionModeBitmap(foreign);
    }
    if (paintAsBitmap) {
        try {
            super.renderSVGDocument(context, doc);
        } catch (IOException ioe) {
            SVGEventProducer eventProducer = SVGEventProducer.Provider
                    .get(context.getUserAgent().getEventBroadcaster());
            eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc));
        }
        return;
    }

    //Controls whether text painted by Batik is generated using text or path operations
    boolean strokeText = false;
    Configuration cfg = psInfo.getHandlerConfiguration();
    if (cfg != null) {
        strokeText = cfg.getChild("stroke-text", true).getValueAsBoolean(strokeText);
    }

    SVGUserAgent ua = new SVGUserAgent(context.getUserAgent(), new AffineTransform());

    PSGraphics2D graphics = new PSGraphics2D(strokeText, gen);
    graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());

    BridgeContext ctx = new PSBridgeContext(ua, (strokeText ? null : psInfo.fontInfo),
            context.getUserAgent().getFactory().getImageManager(),
            context.getUserAgent().getImageSessionContext());

    //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 = psInfo.getWidth() / w;
    float sy = psInfo.getHeight() / h;

    ctx = null;

    try {
        gen.commentln("%FOPBeginSVG");
        gen.saveGraphicsState();
        /*
         * Clip to the svg area.
         * Note: To have the svg overlay (under) a text area then use
         * an fo:block-container
         */
        gen.writeln("newpath");
        gen.defineRect(xOffset / 1000f, yOffset / 1000f, psInfo.getWidth() / 1000f, psInfo.getHeight() / 1000f);
        gen.writeln("clip");

        // transform so that the coordinates (0,0) is from the top left
        // and positive is down and to the right. (0,0) is where the
        // viewBox puts it.
        gen.concatMatrix(sx, 0, 0, sy, xOffset / 1000f, yOffset / 1000f);

        /*
        SVGSVGElement svg = ((SVGDocument)doc).getRootElement();
        AffineTransform at = ViewBox.getPreserveAspectRatioTransform(svg,
            psInfo.getWidth() / 1000f, psInfo.getHeight() / 1000f, ctx);
        if (!at.isIdentity()) {
        double[] vals = new double[6];
        at.getMatrix(vals);
        gen.concatMatrix(vals);
        }*/

        AffineTransform transform = new AffineTransform();
        // scale to viewbox
        transform.translate(xOffset, yOffset);
        gen.getCurrentState().concatMatrix(transform);
        try {
            root.paint(graphics);
        } catch (Exception e) {
            SVGEventProducer eventProducer = SVGEventProducer.Provider
                    .get(context.getUserAgent().getEventBroadcaster());
            eventProducer.svgRenderingError(this, e, getDocumentURI(doc));
        }

        gen.restoreGraphicsState();
        gen.commentln("%FOPEndSVG");
    } catch (IOException ioe) {
        SVGEventProducer eventProducer = SVGEventProducer.Provider
                .get(context.getUserAgent().getEventBroadcaster());
        eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc));
    }
}

From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java

/**
 * Renders this image// w  w  w .ja  va  2s .co  m
 * 
 * @return The image data
 */
private final byte[] render() throws IOException {
    Graphics2D gfx = (Graphics2D) this.image.getGraphics();
    if (config.isFontAntialiasing())
        gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    int curWidth = config.getTextMarginLeft();
    FontRenderContext ctx = new FontRenderContext(null, config.isFontAntialiasing(), false);
    for (int i = 0; i < charAttsList.size(); i++) {
        CharAttributes cf = (CharAttributes) charAttsList.get(i);
        TextLayout text = new TextLayout(cf.getChar() + "", getFont(cf.getName()), ctx); //gfx.getFontRenderContext());
        AffineTransform textAt = new AffineTransform();
        textAt.translate(curWidth, this.height - cf.getRise());
        if (cf.getRotation() != 0) {
            textAt.rotate(cf.getRotation());
        }
        if (cf.getShearX() > 0.0)
            textAt.shear(cf.getShearX(), cf.getShearY());
        Shape shape = text.getOutline(textAt);
        curWidth += shape.getBounds().getWidth() + config.getTextSpacing();
        if (config.isUseImageBackground())
            gfx.setColor(Color.BLACK);
        else
            gfx.setXORMode(Color.BLACK);
        gfx.fill(shape);
    }
    if (config.isEffectsNoise()) {
        noiseEffects(gfx, image);
    }
    if (config.isUseTimestamp()) {
        if (config.isEffectsNoise())
            gfx.setColor(Color.WHITE);
        else
            gfx.setColor(Color.BLACK);

        TimeZone tz = TimeZone.getTimeZone(config.getTimestampTZ());
        Calendar cal = new GregorianCalendar(tz);
        SimpleDateFormat formatter;
        if (config.isUseTimestamp24hr())
            formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
        else
            formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a, z");
        formatter.setTimeZone(tz);
        Font font = gfx.getFont();
        Font newFont = new Font(font.getName(), font.getStyle(), config.getTimestampFontSize());
        gfx.setFont(newFont);
        gfx.drawString(formatter.format(cal.getTime()), config.getTextMarginLeft() * 4, this.height - 1);
    }

    return toImageData(image);
}

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

private void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException {
    graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
    setClip();//from ww  w.  ja v  a2  s .  co m
    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.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   ww w  . j a v  a2s. 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.esa.nest.dat.layers.maptools.components.CompassComponent.java

public void render(final Graphics2D graphics, final ScreenPixelConverter screenPixel) {
    if (Double.isNaN(angle))
        return;/*from w  w w  .j  ava2  s. co m*/

    final AffineTransform transformSave = graphics.getTransform();
    try {
        final AffineTransform transform = screenPixel.getImageTransform(transformSave);

        final double scale = (marginPct * 2 * rasterWidth) / (double) image.getWidth();
        transform.translate(point1.x, point1.y);
        transform.scale(scale, scale);
        transform.rotate(angle);

        graphics.drawRenderedImage(image, transform);
    } finally {
        graphics.setTransform(transformSave);
    }
}

From source file:org.evors.rs.ui.sandpit.SandPitCamera.java

/**
 * Get the value of transform/*from  w w w  .j  av  a  2s. com*/
 *
 * @return the value of transform
 */
public AffineTransform getTransform() {
    AffineTransform returnTransform = new AffineTransform();
    Vector2D currentPosScreenCoord = new Vector2D(getScale(), getCurrentPosWorldCoord());
    Vector2D halfWindow = getHalfWindowSize();
    returnTransform.translate(currentPosScreenCoord.getX() + halfWindow.getX(),
            currentPosScreenCoord.getY() + halfWindow.getY());
    returnTransform.scale(getScale(), -getScale());

    return returnTransform;
}

From source file:org.freecine.filmscan.ScanStrip.java

/**
 Calculate the affine transform from scanStrip to a single frame (frame 
 rotated to straight position, top left corner translated to (0,0)
 @param frame//  ww  w .  j  a va2 s.  co  m
 @return
 */
AffineTransform getFrameXform(int frame) {
    /**
     Estimate film rotation from max 5 perforations
     */

    int f1 = frame - 1;
    int f2 = frame + 1;
    int x1 = (f1 >= 0) ? perforations.get(f1).x : perforations.get(0).x;
    int x2 = (f2 < perforations.size()) ? perforations.get(f2).x : perforations.get(perforations.size() - 1).x;
    int y1 = (f1 >= 0) ? perforations.get(f1).y : perforations.get(0).y;
    int y2 = (f2 < perforations.size()) ? perforations.get(f2).y : perforations.get(perforations.size() - 1).y;
    double rot = Math.atan2((double) x2 - x1, (double) (y2 - y1));
    // Translate the center of perforation to origin

    AffineTransform xform = new AffineTransform();
    xform.translate(0, FRAME_HEIGHT / 2);
    xform.rotate(rot);
    xform.translate(-perforations.get(frame).x, -perforations.get(frame).y);
    //         System.out.println( String.format( "frame %d: (%d, %d), rot %f", 
    //                 frame,perforations.get(frame).x, -perforations.get(frame).y, rot ));         
    return xform;
}

From source file:org.jcurl.core.base.Collider.java

/**
 * Compute the trafo to the right handed coordinate-system with origin
 * <code>orig</code> and positive y-axis pointing from <code>a</code> to
 * <code>b</code>./*from  w  w w  .  java 2s  .co  m*/
 * 
 * @param orig
 * @param a
 * @param b
 * @param mat
 * @return the given matrix
 */
public static AffineTransform getInverseTrafo(final Point2D orig, final Point2D a, final Point2D b,
        final AffineTransform mat) {
    double dx = b.getX() - a.getX();
    double dy = b.getY() - a.getY();
    final double d = Math.sqrt(dx * dx + dy * dy);
    dx /= d;
    dy /= d;
    mat.setTransform(dy, -dx, dx, dy, 0, 0);
    mat.translate(-orig.getX(), -orig.getY());
    return mat;
}

From source file:org.jcurl.core.impl.ColliderBase.java

/**
 * Compute the inverse speed transformation to the right handed, moving
 * coordinate-system with relative speed <code>v0</code> and positive
 * y-axis pointing from <code>a</code> to <code>b</code>.
 * //  w ww  .  j  a va  2 s . co m
 * TODO Maybe thios should operate on {@link Rock}s rather than
 * {@link Point2D}s?
 * 
 * @param v0
 * @param a
 * @param b
 * @param mat
 * @return the given matrix
 */
public static AffineTransform getInverseTrafo(final Point2D v0, final Point2D a, final Point2D b,
        final AffineTransform mat) {
    double dx = b.getX() - a.getX();
    double dy = b.getY() - a.getY();
    final double d = Math.sqrt(dx * dx + dy * dy);
    dx /= d;
    dy /= d;
    mat.setTransform(dy, -dx, dx, dy, 0, 0);
    mat.translate(-v0.getX(), -v0.getY());
    return mat;
}