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:PrintCanvas3D.java

public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {

    if (pi >= 1) {
        return Printable.NO_SUCH_PAGE;
    }/*  ww w . j a v a2s.  c  o m*/

    Graphics2D g2d = (Graphics2D) g;
    //g2d.translate(pf.getImageableX(), pf.getImageableY());
    AffineTransform t2d = new AffineTransform();
    t2d.translate(pf.getImageableX(), pf.getImageableY());
    double xscale = pf.getImageableWidth() / (double) bImage.getWidth();
    double yscale = pf.getImageableHeight() / (double) bImage.getHeight();
    double scale = Math.min(xscale, yscale);
    t2d.scale(scale, scale);
    try {
        g2d.drawImage(bImage, t2d, this);
    } catch (Exception ex) {
        ex.printStackTrace();
        return Printable.NO_SUCH_PAGE;
    }
    return Printable.PAGE_EXISTS;
}

From source file:org.geomajas.plugin.rasterizing.layer.RasterDirectLayer.java

protected void addImage(Graphics2D graphics, ImageResult imageResult, MapViewport viewport) throws IOException {
    Rectangle screenArea = viewport.getScreenArea();
    ReferencedEnvelope worldBounds = viewport.getBounds();
    // convert map bounds to application bounds
    double printScale = screenArea.getWidth() / worldBounds.getWidth();
    if (tileScale < 0) {
        tileScale = printScale;//w ww .j  a va  2s  . c o m
    }
    Envelope applicationBounds = new Envelope((worldBounds.getMinX()) * printScale,
            (worldBounds.getMaxX()) * printScale, -(worldBounds.getMinY()) * printScale,
            -(worldBounds.getMaxY()) * printScale);
    Bbox imageBounds = imageResult.getRasterImage().getBounds();
    // find transform between image bounds and application bounds
    double tx = (imageBounds.getX() * printScale / tileScale - applicationBounds.getMinX());
    double ty = (imageBounds.getY() * printScale / tileScale - applicationBounds.getMinY());
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageResult.getImage()));
    double scaleX = imageBounds.getWidth() / image.getWidth() * printScale / tileScale;
    double scaleY = imageBounds.getHeight() / image.getHeight() * printScale / tileScale;
    AffineTransform transform = new AffineTransform();
    transform.translate(tx, ty);
    transform.scale(scaleX, scaleY);
    if (log.isDebugEnabled()) {
        log.debug("adding image, width=" + image.getWidth() + ",height=" + image.getHeight() + ",x=" + tx
                + ",y=" + ty);
    }
    // opacity
    log.debug("before drawImage");
    // create a copy to apply transform
    Graphics2D g = (Graphics2D) graphics.create();
    // apply opacity to image off-graphics to avoid interference with whatever opacity model is used by graphics
    BufferedImage opaqueCopy = makeOpaque(image);
    g.drawImage(opaqueCopy, transform, null);
    log.debug("after drawImage");
}

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private void generaImagenDamage(ShapeView fondo, List<DamageDetailsVB> danios, File outputfile, int width,
        int height) {
    try {//from w w w  .j  a v a2s  .  c  o m
        Point contexto = new Point((width - fondo.getShapeWidth()) / 2, (height - fondo.getShapeHeight()) / 2);
        BufferedImage off_Image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = off_Image.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, width, height);
        AffineTransform saveXform = g2.getTransform();
        AffineTransform toCenterAt = new AffineTransform();
        toCenterAt.translate(contexto.getX(), contexto.getY());
        g2.transform(toCenterAt);
        fondo.paint(g2);
        g2.setTransform(saveXform);
        for (DamageDetailsVB x : danios) {
            DamageDetailGraphicsView obj = new DamageDetailGraphicsView();
            obj.setPosicion(new Point(x.getX(), x.getY()));
            obj.setContexto(contexto);
            if (x.getX() <= fondo.getShapeWidth() / 2) {
                if (x.getY() <= fondo.getShapeHeight() / 2) {
                    obj.setOrientacion(DamageDetailGraphicsView.SuperiorIzquierda);
                } else {
                    obj.setOrientacion(DamageDetailGraphicsView.InferiorIzquierda);
                }
            } else {
                if (x.getY() <= fondo.getShapeHeight() / 2) {
                    obj.setOrientacion(DamageDetailGraphicsView.SuperiorDerecha);
                } else {
                    obj.setOrientacion(DamageDetailGraphicsView.InferiorDerecha);
                }
            }
            obj.setCategoria(x.getCategoria());
            obj.setCaracteristica(x.getCaracteristica());
            obj.paint(g2);
        }
        saveJPG(off_Image, outputfile);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private void generaSVGImagenDamage(ShapeView fondo, List<DamageDetailsVB> danios, File outputfile, int width,
        int height) {
    // Get a DOMImplementation.
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();

    // Create an instance of org.w3c.dom.Document.
    String svgNS = "http://www.w3.org/2000/svg";
    Document document = domImpl.createDocument(svgNS, "svg", null);

    // Create an instance of the SVG Generator.
    SVGGraphics2D g2 = new SVGGraphics2D(document);
    // pintar./*from w w  w.  j  ava  2s .  c  om*/
    g2.setSVGCanvasSize(new java.awt.Dimension(width, height));
    Point contexto = new Point((width - fondo.getShapeWidth()) / 2, (height - fondo.getShapeHeight()) / 2);
    g2.setColor(Color.WHITE);
    g2.fillRect(0, 0, width, height);
    AffineTransform saveXform = g2.getTransform();
    AffineTransform toCenterAt = new AffineTransform();
    toCenterAt.translate(contexto.getX(), contexto.getY());
    g2.transform(toCenterAt);
    fondo.paint(g2);
    g2.setTransform(saveXform);
    for (DamageDetailsVB x : danios) {
        DamageDetailGraphicsView obj = new DamageDetailGraphicsView();
        obj.setFontSize(esquemaFontSize);
        obj.setPosicion(new Point(x.getX(), x.getY()));
        obj.setContexto(contexto);
        if (x.getX() <= fondo.getShapeWidth() / 2) {
            if (x.getY() <= fondo.getShapeHeight() / 2) {
                obj.setOrientacion(DamageDetailGraphicsView.SuperiorIzquierda);
                //obj.setOrientacion(DamageDetailGraphicsView.SuperiorDerecha);
            } else {
                obj.setOrientacion(DamageDetailGraphicsView.InferiorIzquierda);
                //obj.setOrientacion(DamageDetailGraphicsView.InferiorDerecha);
            }
        } else {
            if (x.getY() <= fondo.getShapeHeight() / 2) {
                obj.setOrientacion(DamageDetailGraphicsView.SuperiorDerecha);
                //obj.setOrientacion(DamageDetailGraphicsView.SuperiorIzquierda);
            } else {
                obj.setOrientacion(DamageDetailGraphicsView.InferiorDerecha);
                //obj.setOrientacion(DamageDetailGraphicsView.InferiorIzquierda);
            }
        }
        obj.setCategoria(x.getCategoria());
        obj.setCaracteristica(x.getCaracteristica());
        obj.paint(g2);
    }
    try {
        g2.stream(outputfile.getCanonicalPath());
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:be.fedict.eidviewer.gui.printing.IDPrintout.java

public int print(Graphics graphics, PageFormat pageFormat, int pageNumber) throws PrinterException {
    // we only support printing all in one single page
    if (pageNumber > 0)
        return Printable.NO_SUCH_PAGE;

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("width", pageFormat.getWidth()).append("height", pageFormat.getHeight())
            .append("imageableWidth", pageFormat.getImageableWidth())
            .append("imageableHeight", pageFormat.getImageableHeight())
            .append("imageableX", pageFormat.getImageableX()).append("imageableY", pageFormat.getImageableY())
            .append("orientation", pageFormat.getOrientation())
            .append("paper.width", pageFormat.getPaper().getWidth())
            .append("paper.height", pageFormat.getPaper().getHeight())
            .append("paper.imageableWidth", pageFormat.getPaper().getImageableWidth())
            .append("paper.imageableHeight", pageFormat.getPaper().getImageableHeight())
            .append("paper.imageableX", pageFormat.getPaper().getImageableX())
            .append("paper.imageableY", pageFormat.getPaper().getImageableY()).toString());

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("clip.width", graphics.getClipBounds().width)
            .append("clip.height", graphics.getClipBounds().height).append("clip.x", graphics.getClipBounds().x)
            .append("clip.y", graphics.getClipBounds().y).toString());

    // translate graphics2D with origin at top left first imageable location
    Graphics2D graphics2D = (Graphics2D) graphics;
    graphics2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

    // keep imageable width and height as variables for clarity (we use them often)
    float imageableWidth = (float) pageFormat.getImageableWidth();
    float imageableHeight = (float) pageFormat.getImageableHeight();

    // Coat of Arms images are stored at approx 36 DPI, scale 1/2 to get to Java default of 72DPI
    AffineTransform coatOfArmsTransform = new AffineTransform();
    coatOfArmsTransform.scale(0.5, 0.5);

    // photo images are stored at approx 36 DPI, scale 1/2 to get to Java default of 72DPI
    AffineTransform photoTransform = new AffineTransform();
    photoTransform.scale(0.5, 0.5);//from   w  ww .  j a  va  2 s  .  com
    photoTransform.translate((imageableWidth * 2) - (photo.getWidth(this)), 0);

    // make sure foreground is black, and draw coat of Arms and photo at the top of the page
    // using the transforms to scale them to 72DPI.
    graphics2D.setColor(Color.BLACK);
    graphics2D.drawImage(coatOfArms, coatOfArmsTransform, null);
    graphics2D.drawImage(photo, photoTransform, null);

    // calculate some sizes that need to take into account the scaling of the graphics, to avoid dragging
    // those non-intuitive "/2" further along in the code.
    float headerHeight = (float) (coatOfArms.getHeight(this)) / 2;
    float coatOfArmsWidth = (float) (coatOfArms.getWidth(this)) / 2;
    float photoWidth = (float) (photo.getWidth(this)) / 2;
    float headerSpaceBetweenImages = imageableWidth
            - (coatOfArmsWidth + photoWidth + (SPACE_BETWEEN_ITEMS * 2));

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("headerHeight", headerHeight)
            .append("coatOfArmsWidth", coatOfArmsWidth).append("photoWidth", photoWidth)
            .append("headerSpaceBetweenImages", headerSpaceBetweenImages).toString());

    // get localised strings for card type. We'll take a new line every time a ";" is found in the resource
    String[] cardTypeStr = (bundle.getString("type_" + this.identity.getDocumentType().toString())
            .toUpperCase()).split(";");

    // if a "mention" is present, append it so it appears below the card type string, between brackets

    if (identity.getSpecialOrganisation() != SpecialOrganisation.UNSPECIFIED) {
        String mention = TextFormatHelper.getSpecialOrganisationString(bundle,
                identity.getSpecialOrganisation());
        if (mention != null && !mention.isEmpty()) {
            String[] cardTypeWithMention = new String[cardTypeStr.length + 1];
            System.arraycopy(cardTypeStr, 0, cardTypeWithMention, 0, cardTypeStr.length);
            cardTypeWithMention[cardTypeStr.length] = "(" + mention + ")";
            cardTypeStr = cardTypeWithMention;
        }
    }

    // iterate from MAXIMAL_FONT_SIZE, calculating how much space would be required to fit the card type strings
    // stop when a font size is found where they all fit the space between the graphics in an orderly manner
    boolean sizeFound = false;
    int fontSize;
    for (fontSize = TITLE_MAXIMAL_FONT_SIZE; (fontSize >= MINIMAL_FONT_SIZE) && (!sizeFound); fontSize--) // count down slowly until we find one that fits nicely
    {
        logger.log(Level.FINE, "fontSize=" + fontSize + " sizeFound=" + sizeFound);
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize));
        sizeFound = (ImageUtilities.getTotalStringWidth(graphics2D, cardTypeStr) < headerSpaceBetweenImages)
                && (ImageUtilities.getTotalStringHeight(graphics2D, cardTypeStr) < headerHeight);
    }

    // unless with extremely small papers, a size should always have been found.
    // draw the card type strings, centered, between the images at the top of the page
    if (sizeFound) {
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize + 1));
        float cardTypeHeight = cardTypeStr.length * ImageUtilities.getStringHeight(graphics2D);
        float cardTypeBaseLine = ((headerHeight - cardTypeHeight) / 2) + ImageUtilities.getAscent(graphics2D);
        float cardTypeLineHeight = ImageUtilities.getStringHeight(graphics2D);

        logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
                .append("cardTypeHeight", cardTypeHeight).append("cardTypeBaseLine", cardTypeBaseLine)
                .append("cardTypeLineHeight", cardTypeLineHeight).toString());

        for (int i = 0; i < cardTypeStr.length; i++) {
            float left = (coatOfArmsWidth + SPACE_BETWEEN_ITEMS
                    + (headerSpaceBetweenImages - ImageUtilities.getStringWidth(graphics2D, cardTypeStr[i]))
                            / 2);
            float leading = (float) cardTypeLineHeight * i;
            graphics2D.drawString(cardTypeStr[i], left, cardTypeBaseLine + leading);
        }
    }

    // populate idAttributes with all the information from identity and address
    // as well as date printed and some separators
    List<IdentityAttribute> idAttributes = populateAttributeList();

    // draw a horizontal line just below the header (images + card type titles)
    graphics2D.drawLine(0, (int) headerHeight, (int) imageableWidth, (int) headerHeight);

    // calculate how much space is left between the header and the bottom of the imageable area

    headerHeight += 32; // take some distance from header

    float imageableDataHeight = imageableHeight - headerHeight;
    float totalDataWidth = 0, totalDataHeight = 0;
    float labelWidth, widestLabelWidth = 0;
    float valueWidth, widestValueWidth = 0;

    // iterate from MAXIMAL_FONT_SIZE, calculating how much space would be required to fit the information in idAttributes into
    // the space between the header and the bottom of the imageable area
    // stop when a font size is found where it all fits in an orderly manner
    sizeFound = false;
    for (fontSize = MAXIMAL_FONT_SIZE; (fontSize >= MINIMAL_FONT_SIZE) && (!sizeFound); fontSize--) // count down slowly until we find one that fits nicely
    {
        logger.log(Level.FINE, "fontSize=" + fontSize + " sizeFound=" + sizeFound);
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize));

        widestLabelWidth = 0;
        widestValueWidth = 0;

        for (IdentityAttribute attribute : idAttributes) {
            if (attribute == SEPARATOR)
                continue;

            labelWidth = ImageUtilities.getStringWidth(graphics2D, attribute.getLabel());
            valueWidth = ImageUtilities.getStringWidth(graphics2D, attribute.getValue());
            if (labelWidth > widestLabelWidth)
                widestLabelWidth = labelWidth;
            if (valueWidth > widestValueWidth)
                widestValueWidth = valueWidth;
        }

        totalDataWidth = widestLabelWidth + SPACE_BETWEEN_ITEMS + widestValueWidth;
        totalDataHeight = ImageUtilities.getStringHeight(graphics2D)
                + (ImageUtilities.getStringHeight(graphics2D) * idAttributes.size());

        if ((totalDataWidth < imageableWidth) && (totalDataHeight < imageableDataHeight))
            sizeFound = true;
    }

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("widestLabelWidth", widestLabelWidth).append("widestValueWidth", widestValueWidth)
            .append("totalDataWidth", totalDataWidth).append("totalDataHeight", totalDataHeight).toString());

    // unless with extremely small papers, a size should always have been found.
    // draw the identity, addess and date printed information, in 2 columns, centered inside the
    // space between the header and the bottom of the imageable area
    if (sizeFound) {
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize));
        float labelsLeft = (imageableWidth - totalDataWidth) / 2;
        float valuesLeft = labelsLeft + widestLabelWidth + SPACE_BETWEEN_ITEMS;
        float dataLineHeight = ImageUtilities.getStringHeight(graphics2D);
        float dataTop = dataLineHeight + headerHeight + ((imageableDataHeight - totalDataHeight) / 2);
        float lineNumber = 0;

        logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("labelsLeft", labelsLeft)
                .append("valuesLeft", valuesLeft).append("dataLineHeight", dataLineHeight)
                .append("dataTop", dataTop).toString());

        for (IdentityAttribute attribute : idAttributes) {
            if (attribute != SEPARATOR) // data
            {
                graphics2D.setColor(attribute.isRelevant() ? Color.BLACK : Color.LIGHT_GRAY);
                graphics2D.drawString(attribute.getLabel(), labelsLeft,
                        dataTop + (lineNumber * dataLineHeight));
                graphics2D.drawString(attribute.getValue(), valuesLeft,
                        dataTop + (lineNumber * dataLineHeight));
            } else // separator
            {
                int y = (int) (((dataTop + (lineNumber * dataLineHeight) + (dataLineHeight / 2)))
                        - ImageUtilities.getAscent(graphics2D));
                graphics2D.setColor(Color.BLACK);
                graphics2D.drawLine((int) labelsLeft, y, (int) (labelsLeft + totalDataWidth), y);
            }
            lineNumber++;
        }
    }

    // tell Java printing that all this makes for a page worth printing :-)
    return Printable.PAGE_EXISTS;
}

From source file:com.ctsim.dmi.MainFrame.java

private void drawPin() {

    //double speed = 100 * (double) x / 1013;
    String speedShow = df.format(App.speed);
    int strWidth;

    AffineTransform restore = g2.getTransform();
    AffineTransform trans = new AffineTransform();
    trans.translate(266, 90);
    trans.rotate(Math.toRadians(getPinAngle(App.speed)), 40, 165);
    g2.setTransform(trans);//  www  .  j  a va  2  s.c  o m
    g2.drawImage(speedoPinWhite, 0, 0, this);
    g2.setTransform(restore);

    // Draw actual speed
    g2.setFont(new Font("Loma", Font.BOLD, 30));
    g2.setColor(Color.BLACK);
    FontMetrics metrics = g2.getFontMetrics();
    strWidth = metrics.stringWidth(speedShow);

    g2.drawString(String.valueOf(speedShow), 306 - strWidth / 2, 265);
}

From source file:org.jax.haplotype.analysis.visualization.SimplePhylogenyTreeImageFactory.java

/**
 * Get the label shape for the given tree node
 * @param treeNode//from   w  w  w .  ja v  a 2s.  c o  m
 *          the tree node
 * @param frc
 *          the font rendering context
 * @return
 *          the label shape
 */
private Shape getLabelShape(VisualTreeNode treeNode, FontRenderContext frc) {
    // convert the strain list to a comma separated list then wrap it
    List<String> strainList = treeNode.getPhylogenyTreeNode().getStrains();
    int strainCount = strainList.size();
    StringBuffer commaSeparatedStrains = new StringBuffer();
    for (int i = 0; i < strainCount; i++) {
        if (i >= 1) {
            commaSeparatedStrains.append(", ");
        }
        commaSeparatedStrains.append(strainList.get(i));
    }
    String[] wrappedStrains = TextWrapper.wrapText(commaSeparatedStrains.toString(), NODE_LABEL_WRAP_LIMIT);

    Shape textShape = Java2DUtils.createCenteredMultilineTextShape(wrappedStrains, LABEL_FONT, frc);
    AffineTransform transform = new AffineTransform();
    transform.translate(treeNode.getPosition().getX(), treeNode.getPosition().getY());
    textShape = transform.createTransformedShape(textShape);

    return textShape;
}

From source file:AppSpringLayout.java

protected BufferedImage mirrorImage(BufferedImage imageToFlip) {

    // Flip the image horizontally
    AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
    tx.translate(-imageToFlip.getWidth(null), 0);
    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    imageToFlip = op.filter(imageToFlip, null);

    return imageToFlip;
}

From source file:HelloUniverse.java

private void drawZPip(Graphics2D g2, float zAngle) {
    AffineTransform trans = new AffineTransform();
    Color origColor = g2.getColor();

    trans.translate(margin, margin);
    trans.rotate(zAngle, diameter / 2, diameter / 2);

    g2.setXORMode(getBackground());//from ww  w  .  j a va  2  s  . c o  m
    g2.setTransform(trans);
    g2.setColor(Color.red);
    g2.fillPolygon(zPip);

    // Reset graphics context
    trans.setToIdentity();
    g2.setTransform(trans);
    g2.setColor(origColor);
    g2.setPaintMode();
}

From source file:edu.uci.ics.jung.visualization.picking.ShapePickSupport.java

/**
 * Retrieves the shape template for <code>e</code> and
 * transforms it according to the positions of its endpoints
 * in <code>layout</code>./*from  w  w  w  .jav  a  2 s.co  m*/
 * @param layout the <code>Layout</code> which specifies
 * <code>e</code>'s endpoints' positions
 * @param e the edge whose shape is to be returned
 * @return
 */
private Shape getTransformedEdgeShape(Layout<V, E> layout, E e) {
    Pair<V> pair = layout.getGraph().getEndpoints(e);
    V v1 = pair.getFirst();
    V v2 = pair.getSecond();
    boolean isLoop = v1.equals(v2);
    Point2D p1 = vv.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, layout.transform(v1));
    Point2D p2 = vv.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, layout.transform(v2));
    if (p1 == null || p2 == null)
        return null;
    float x1 = (float) p1.getX();
    float y1 = (float) p1.getY();
    float x2 = (float) p2.getX();
    float y2 = (float) p2.getY();

    // translate the edge to the starting vertex
    AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1);

    Shape edgeShape = vv.getRenderContext().getEdgeShapeTransformer()
            .transform(Context.<Graph<V, E>, E>getInstance(vv.getGraphLayout().getGraph(), e));
    if (isLoop) {
        // make the loops proportional to the size of the vertex
        Shape s2 = vv.getRenderContext().getVertexShapeTransformer().transform(v2);
        Rectangle2D s2Bounds = s2.getBounds2D();
        xform.scale(s2Bounds.getWidth(), s2Bounds.getHeight());
        // move the loop so that the nadir is centered in the vertex
        xform.translate(0, -edgeShape.getBounds2D().getHeight() / 2);
    } else {
        float dx = x2 - x1;
        float dy = y2 - y1;
        // rotate the edge to the angle between the vertices
        double theta = Math.atan2(dy, dx);
        xform.rotate(theta);
        // stretch the edge to span the distance between the vertices
        float dist = (float) Math.sqrt(dx * dx + dy * dy);
        xform.scale(dist, 1.0f);
    }

    // transform the edge to its location and dimensions
    edgeShape = xform.createTransformedShape(edgeShape);
    return edgeShape;
}