Example usage for java.awt Graphics2D translate

List of usage examples for java.awt Graphics2D translate

Introduction

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

Prototype

public abstract void translate(double tx, double ty);

Source Link

Document

Concatenates the current Graphics2D Transform with a translation transform.

Usage

From source file:fr.ign.cogit.geoxygene.appli.layer.LayerViewAwtPanel.java

@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
    if (pageIndex >= 1) {
        return Printable.NO_SUCH_PAGE;
    }//ww  w .j  a  v a 2s .c om
    Graphics2D g2d = (Graphics2D) graphics;
    // translate to the upper left corner of the page format
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    // translate to the middle of the page format
    g2d.translate(pageFormat.getImageableWidth() / 2, pageFormat.getImageableHeight() / 2);
    Dimension d = this.getSize();
    double scale = Math.min(pageFormat.getImageableWidth() / d.width,
            pageFormat.getImageableHeight() / d.height);
    if (scale < 1.0) {
        g2d.scale(scale, scale);
    }
    // translate of half the size of the graphics to paint for it to be
    // centered
    g2d.translate(-d.width / 2.0, -d.height / 2.0);
    // copy the rendered layers into the graphics
    this.getRenderingManager().copyTo(g2d);
    return Printable.PAGE_EXISTS;
}

From source file:com.alvermont.terraj.util.io.ImagePrinter.java

/**
 * Render an image for printing.// w w  w  .  ja va2  s.c  o  m
 *
 * @param graphics The graphics context to print on
 * @param pageFormat The page format being used
 * @param pageIndex The page being printed
 * @throws java.awt.print.PrinterException If there is an error in printing
 * @return An indication of the result of page rendering for this page
 */
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
    final Graphics2D g2 = (Graphics2D) graphics;

    // we only expect to be printing 1 page as the image is scaled
    if (pageIndex >= 1) {
        return Printable.NO_SUCH_PAGE;
    }

    // translate the coordinate system to match up the image with 
    // the printable area
    g2.translate(getFormat().getImageableX(), pageFormat.getImageableY());

    final Rectangle componentBounds = new Rectangle(getImage().getWidth(), getImage().getHeight());
    g2.translate(-componentBounds.x, -componentBounds.y);

    // scale the image to fit
    scaleToFit(true);
    g2.scale(getScaleX(), getScaleY());

    // render the image
    g2.drawImage(getImage(), null, 0, 0);

    // done
    return Printable.PAGE_EXISTS;
}

From source file:org.apache.fop.render.pcl.PCLPainter.java

/** {@inheritDoc} */
public void drawLine(final Point start, final Point end, final int width, final Color color,
        final RuleStyle style) throws IFException {
    if (isSpeedOptimized()) {
        super.drawLine(start, end, width, color, style);
        return;// w ww  .ja v  a  2s. com
    }
    final Rectangle boundingBox = getLineBoundingBox(start, end, width);
    final Dimension dim = boundingBox.getSize();

    Graphics2DImagePainter painter = new Graphics2DImagePainter() {

        public void paint(Graphics2D g2d, Rectangle2D area) {
            g2d.translate(-boundingBox.x, -boundingBox.y);

            Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state);
            try {
                painter.drawLine(start, end, width, color, style);
            } catch (IFException e) {
                //This should never happen with the Java2DPainter
                throw new RuntimeException("Unexpected error while painting a line", e);
            }
        }

        public Dimension getImageSize() {
            return dim.getSize();
        }

    };
    paintMarksAsBitmap(painter, boundingBox);
}

From source file:org.apache.fop.render.pcl.PCLPainter.java

/** {@inheritDoc} */
public void drawBorderRect(final Rectangle rect, final BorderProps before, final BorderProps after,
        final BorderProps start, final BorderProps end) throws IFException {
    if (isSpeedOptimized()) {
        super.drawBorderRect(rect, before, after, start, end);
        return;/* w  ww  . j av a  2  s  .  c  o m*/
    }
    if (before != null || after != null || start != null || end != null) {
        final Rectangle boundingBox = rect;
        final Dimension dim = boundingBox.getSize();

        Graphics2DImagePainter painter = new Graphics2DImagePainter() {

            public void paint(Graphics2D g2d, Rectangle2D area) {
                g2d.translate(-rect.x, -rect.y);

                Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state);
                try {
                    painter.drawBorderRect(rect, before, after, start, end);
                } catch (IFException e) {
                    //This should never happen with the Java2DPainter
                    throw new RuntimeException("Unexpected error while painting borders", e);
                }
            }

            public Dimension getImageSize() {
                return dim.getSize();
            }

        };
        paintMarksAsBitmap(painter, boundingBox);
    }
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.reporting.ProfilesComparisonReportChartCanvas.java

protected void paintComponent(Graphics g) {

    // prepare graphic object
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // set clipping area
    if (is_printing) {
        g2d.translate(-draw_area.x, -draw_area.y);
        g2d.setClip(draw_area);//from  ww  w .j ava  2s .c  o  m
    }

    //paint canvas background
    if (!is_printing) {
        g2d.setColor(getBackground());
        g2d.fillRect(0, 0, getWidth(), getHeight());
    }

    // paint white background on drawing area    
    g2d.setColor(Color.white);
    g2d.fillRect(draw_area.x, draw_area.y, draw_area.width, draw_area.height);
    if (!is_printing) {
        g2d.setColor(Color.black);
        g2d.draw(draw_area);
    }

    // paint
    paintChart(g2d);

    // dispose graphic object
    g2d.dispose();

    revalidate();
}

From source file:BookTest.java

public void drawPage(Graphics2D g2, PageFormat pf, int page) {
    if (message.equals(""))
        return;/*ww w.  j  av  a  2  s. c  om*/
    page--; // account for cover page

    drawCropMarks(g2, pf);
    g2.clip(new Rectangle2D.Double(0, 0, pf.getImageableWidth(), pf.getImageableHeight()));
    g2.translate(-page * pf.getImageableWidth(), 0);
    g2.scale(scale, scale);
    FontRenderContext context = g2.getFontRenderContext();
    Font f = new Font("Serif", Font.PLAIN, 72);
    TextLayout layout = new TextLayout(message, f, context);
    AffineTransform transform = AffineTransform.getTranslateInstance(0, layout.getAscent());
    Shape outline = layout.getOutline(transform);
    g2.draw(outline);
}

From source file:LineGraphDrawable.java

/**
 * Draws the bar-graph into the given Graphics2D context in the given area.
 * This method will not draw a graph if the data given is null or empty.
 * //from   w  w  w  .j a va 2 s  .  c om
 * @param graphics
 *          the graphics context on which the bargraph should be rendered.
 * @param drawArea
 *          the area on which the bargraph should be drawn.
 */
public void draw(final Graphics2D graphics, final Rectangle2D drawArea) {
    if (graphics == null) {
        throw new NullPointerException();
    }
    if (drawArea == null) {
        throw new NullPointerException();
    }

    final int height = (int) drawArea.getHeight();
    if (height <= 0) {
        return;
    }

    final Graphics2D g2 = (Graphics2D) graphics.create();
    if (background != null) {
        g2.setPaint(background);
        g2.draw(drawArea);
    }

    if (data == null || data.length == 0) {
        g2.dispose();
        return;
    }

    g2.translate(drawArea.getX(), drawArea.getY());

    float d = getDivisor(data, height);
    final int spacing = getSpacing();
    final int w = (((int) drawArea.getWidth()) - (spacing * (data.length - 1))) / (data.length - 1);

    float min = Float.MAX_VALUE;
    for (int index = 0; index < data.length; index++) {
        Number i = data[index];
        if (i == null) {
            continue;
        }
        final float value = i.floatValue();
        if (value < min) {
            min = value;
        }
    }

    int x = 0;
    int y = -1;

    if (d == 0.0) {
        // special case -- a horizontal straight line
        d = 1.0f;
        y = -height / 2;
    }

    final Line2D.Double line = new Line2D.Double();
    for (int i = 0; i < data.length - 1; i++) {
        final int px1 = x;
        x += (w + spacing);
        final int px2 = x;

        g2.setPaint(color);

        final Number number = data[i];
        final Number nextNumber = data[i + 1];
        if (number == null && nextNumber == null) {
            final float delta = height - ((0 - min) / d);
            line.setLine(px1, y + delta, px2, y + delta);
        } else if (number == null) {
            line.setLine(px1, y + (height - ((0 - min) / d)), px2,
                    y + (height - ((nextNumber.floatValue() - min) / d)));
        } else if (nextNumber == null) {
            line.setLine(px1, y + (height - ((number.floatValue() - min) / d)), px2,
                    y + (height - ((0 - min) / d)));
        } else {
            line.setLine(px1, y + (height - ((number.floatValue() - min) / d)), px2,
                    y + (height - ((nextNumber.floatValue() - min) / d)));
        }
        g2.draw(line);

    }

    g2.dispose();

}

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);/*w  w w .j a  va 2 s  .  c  om*/
    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:LineStyles.java

/** This method draws the example figure */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;
    // Use anti-aliasing to avoid "jaggies" in the lines
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // Define the shape to draw
    GeneralPath shape = new GeneralPath();
    shape.moveTo(xpoints[0], ypoints[0]); // start at point 0
    shape.lineTo(xpoints[1], ypoints[1]); // draw a line to point 1
    shape.lineTo(xpoints[2], ypoints[2]); // and then on to point 2

    // Move the origin to the right and down, creating a margin
    g.translate(20, 40);

    // Now loop, drawing our shape with the three different line styles
    for (int i = 0; i < linestyles.length; i++) {
        g.setColor(Color.gray); // Draw a gray line
        g.setStroke(linestyles[i]); // Select the line style to use
        g.draw(shape); // Draw the shape

        g.setColor(Color.black); // Now use black
        g.setStroke(thindashed); // And the thin dashed line
        g.draw(shape); // And draw the shape again.

        // Highlight the location of the vertexes of the shape
        // This accentuates the cap and join styles we're demonstrating
        for (int j = 0; j < xpoints.length; j++)
            g.fillRect(xpoints[j] - 2, ypoints[j] - 2, 5, 5);

        g.drawString(capNames[i], 5, 105); // Label the cap style
        g.drawString(joinNames[i], 5, 120); // Label the join style

        g.translate(150, 0); // Move over to the right before looping again
    }/*  ww  w  .  j  av  a  2  s.c  o  m*/
}

From source file:org.jahia.services.image.AbstractJava2DImageService.java

public boolean rotateImage(Image image, File outputFile, boolean clockwise) throws IOException {
    BufferedImage originalImage = ((BufferImage) image).getOriginalImage();

    BufferedImage dest = getDestImage(originalImage.getHeight(), originalImage.getWidth(), originalImage);
    // Paint source image into the destination, scaling as needed
    Graphics2D graphics2D = getGraphics2D(dest, OperationType.ROTATE);

    double angle = Math.toRadians(clockwise ? 90 : -90);
    double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
    int w = originalImage.getWidth(), h = originalImage.getHeight();
    int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math.floor(h * cos + w * sin);
    graphics2D.translate((neww - w) / 2, (newh - h) / 2);
    graphics2D.rotate(angle, w / (double) 2, h / (double) 2);
    graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
    if (originalImage.getColorModel() instanceof IndexColorModel) {
        graphics2D.drawImage(originalImage, 0, 0, graphics2D.getBackground(), null);
    } else {//  w  w  w.  j a va2 s  .  c om
        graphics2D.drawImage(originalImage, 0, 0, null);
    }

    // Save destination image
    saveImageToFile(dest, ((BufferImage) image).getMimeType(), outputFile);
    return true;
}