Example usage for java.awt Graphics2D scale

List of usage examples for java.awt Graphics2D scale

Introduction

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

Prototype

public abstract void scale(double sx, double sy);

Source Link

Document

Concatenates the current Graphics2D Transform with a scaling transformation Subsequent rendering is resized according to the specified scaling factors relative to the previous scaling.

Usage

From source file:org.mabb.fontverter.opentype.DebugGlyphDrawer.java

public static void drawGlyph(TtfGlyph glyph) throws IOException {
    BufferedImage image = new BufferedImage(650, 650, BufferedImage.TYPE_INT_RGB);
    Graphics2D gfx = image.createGraphics();

    gfx.translate(0, 300);//from w w w.j a v  a 2s .c  o m
    gfx.scale(1, -1);

    gfx.setColor(Color.white);
    gfx.fillRect(0, -1000, 2060, 2060);
    gfx.setColor(Color.lightGray);
    gfx.translate(100, 50);
    gfx.fillRect(0, 0, 1000, 1000);
    gfx.setColor(Color.BLACK);

    gfx.scale(.05, .05);

    //        gfx.rotate(Math.toRadians(180));
    //        gfx.translate(-2200, -2200);

    Color[] colors = new Color[] { Color.BLACK, Color.MAGENTA, Color.GREEN, Color.BLUE, Color.cyan };
    java.util.List<Path2D.Double> paths = glyph.getPaths();
    for (int i = 0; i < paths.size(); i++) {
        Path2D pathOn = paths.get(i);
        gfx.setColor(colors[i]);

        gfx.draw(pathOn);
    }

    gfx.dispose();

    //        ImageIO.write(image, "jpg", new File("test.jpg"));
}

From source file:org.openstreetmap.josm.tools.ImageProvider.java

public static BufferedImage createImageFromSvg(SVGDiagram svg, Dimension dim) {
    float realWidth = svg.getWidth();
    float realHeight = svg.getHeight();
    int width = Math.round(realWidth);
    int height = Math.round(realHeight);
    Double scaleX = null, scaleY = null;
    if (dim.width != -1) {
        width = dim.width;/*from  w ww  . j  a  v  a2s  . c o m*/
        scaleX = (double) width / realWidth;
        if (dim.height == -1) {
            scaleY = scaleX;
            height = (int) Math.round(realHeight * scaleY);
        } else {
            height = dim.height;
            scaleY = (double) height / realHeight;
        }
    } else if (dim.height != -1) {
        height = dim.height;
        scaleX = scaleY = (double) height / realHeight;
        width = (int) Math.round(realWidth * scaleX);
    }
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = img.createGraphics();
    g.setClip(0, 0, width, height);
    if (scaleX != null) {
        g.scale(scaleX, scaleY);
    }
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    try {
        svg.render(g);
    } catch (SVGException ex) {
        return null;
    }
    return img;
}

From source file:org.pentaho.reporting.designer.core.editor.report.AbstractRenderComponent.java

protected void paintComponent(final Graphics g) {
    if (fpsCalculator.isActive()) {
        fpsCalculator.tick();/* w  w  w  .j  a  v  a2s. com*/
    }

    final Graphics2D g2 = (Graphics2D) g.create();

    g2.setColor(new Color(224, 224, 224));
    g2.fillRect(0, 0, getWidth(), getHeight());

    final int leftBorder = (int) getLeftBorder();
    final int topBorder = (int) getTopBorder();
    final float scaleFactor = getRenderContext().getZoomModel().getZoomAsPercentage();

    // draw the page area ..
    final PageDefinition pageDefinition = getRenderContext().getContextRoot().getPageDefinition();
    final Rectangle2D.Double area = new Rectangle2D.Double(0, 0, pageDefinition.getWidth() * scaleFactor,
            getHeight());
    g2.translate(leftBorder * scaleFactor, topBorder * scaleFactor);
    g2.clip(area);
    g2.setColor(Color.WHITE);
    g2.fill(area);

    // draw the grid (unscaled, but translated)
    final Point2D offset = getOffset();
    if (offset.getX() != 0) {
        // The blackout area is for inline sub-reports and is the area where the subreport is not interested in
        // (so we can clip out).  The blackout area is only visible in the sub-report.
        final Rectangle2D.Double blackoutArea = new Rectangle2D.Double(0, 0, offset.getX() * scaleFactor,
                getHeight());
        g2.setColor(Color.LIGHT_GRAY);
        g2.fill(blackoutArea);
    }
    paintGrid(g2);
    paintElementAlignment(g2);
    g2.dispose();

    final Graphics2D logicalPageAreaG2 = (Graphics2D) g.create();
    // draw the renderable content ...
    logicalPageAreaG2.translate(leftBorder * scaleFactor, topBorder * scaleFactor);
    logicalPageAreaG2.clip(area);
    logicalPageAreaG2.scale(scaleFactor, scaleFactor);

    try {
        final ElementRenderer rendererRoot = getElementRenderer();
        if (rendererRoot != null) {
            if (rendererRoot.draw(logicalPageAreaG2) == false) {
                rendererRoot.handleError(designerContext, renderContext);

                logicalPageAreaG2.scale(1f / scaleFactor, 1f / scaleFactor);
                logicalPageAreaG2.setPaint(Color.WHITE);
                logicalPageAreaG2.fill(area);
            }
        }
    } catch (Exception e) {
        // ignore for now..
        UncaughtExceptionsModel.getInstance().addException(e);
    }

    logicalPageAreaG2.dispose();

    final OverlayRenderer[] renderers = new OverlayRenderer[4];
    renderers[0] = new OverlappingElementOverlayRenderer(getDefaultElement()); // displays the red border for warning
    renderers[1] = new SelectionOverlayRenderer(getDefaultElement());
    renderers[2] = new GuidelineOverlayRenderer(horizontalLinealModel, verticalLinealModel);
    renderers[3] = new SelectionRectangleOverlayRenderer(); // blue box when you shift and drag the region to select multiple
    // elements

    for (int i = 0; i < renderers.length; i++) {
        final OverlayRenderer renderer = renderers[i];
        final Graphics2D selectionG2 = (Graphics2D) g.create();

        renderer.validate(getRenderContext(), scaleFactor, offset);
        renderer.draw(selectionG2,
                new Rectangle2D.Double(getLeftBorder(), getTopBorder(), getWidth(), getHeight()), this);
        selectionG2.dispose();
    }
}

From source file:org.pentaho.reporting.engine.classic.core.layout.output.RenderUtility.java

public static DefaultImageReference createImageFromDrawable(final DrawableWrapper drawable,
        final StrictBounds rect, final StyleSheet box, final OutputProcessorMetaData metaData) {
    final int imageWidth = (int) StrictGeomUtility.toExternalValue(rect.getWidth());
    final int imageHeight = (int) StrictGeomUtility.toExternalValue(rect.getHeight());

    if (imageWidth == 0 || imageHeight == 0) {
        return null;
    }//from   ww w.j a v  a 2 s .  c  o  m

    final double scale = RenderUtility.getNormalizationScale(metaData);
    final Image image = ImageUtils.createTransparentImage((int) (imageWidth * scale),
            (int) (imageHeight * scale));
    final Graphics2D g2 = (Graphics2D) image.getGraphics();

    final Object attribute = box.getStyleProperty(ElementStyleKeys.ANTI_ALIASING);
    if (attribute != null) {
        if (Boolean.TRUE.equals(attribute)) {
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        } else if (Boolean.FALSE.equals(attribute)) {
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
        }

    }
    if (RenderUtility.isFontSmooth(box, metaData)) {
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    } else {
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    }

    g2.scale(scale, scale);
    // the clipping bounds are a sub-area of the whole drawable
    // we only want to print a certain area ...

    final String fontName = (String) box.getStyleProperty(TextStyleKeys.FONT);
    final int fontSize = box.getIntStyleProperty(TextStyleKeys.FONTSIZE, 8);
    final boolean bold = box.getBooleanStyleProperty(TextStyleKeys.BOLD);
    final boolean italics = box.getBooleanStyleProperty(TextStyleKeys.ITALIC);
    if (bold && italics) {
        g2.setFont(new Font(fontName, Font.BOLD | Font.ITALIC, fontSize));
    } else if (bold) {
        g2.setFont(new Font(fontName, Font.BOLD, fontSize));
    } else if (italics) {
        g2.setFont(new Font(fontName, Font.ITALIC, fontSize));
    } else {
        g2.setFont(new Font(fontName, Font.PLAIN, fontSize));
    }

    g2.setStroke((Stroke) box.getStyleProperty(ElementStyleKeys.STROKE));
    g2.setPaint((Paint) box.getStyleProperty(ElementStyleKeys.PAINT));

    drawable.draw(g2, new Rectangle2D.Double(0, 0, imageWidth, imageHeight));
    g2.dispose();

    try {
        return new DefaultImageReference(image);
    } catch (final IOException e1) {
        logger.warn("Unable to fully load a given image. (It should not happen here.)", e1);
        return null;
    }
}

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

/**
 * @param content/*from w w w .  j  a v a2s .  com*/
 * @param image
 */
protected boolean drawImage(final RenderableReplacedContentBox content, Image image) {
    final StyleSheet layoutContext = content.getStyleSheet();
    final boolean shouldScale = layoutContext.getBooleanStyleProperty(ElementStyleKeys.SCALE);

    final int x = (int) StrictGeomUtility.toExternalValue(content.getX());
    final int y = (int) StrictGeomUtility.toExternalValue(content.getY());
    final int width = (int) StrictGeomUtility.toExternalValue(content.getWidth());
    final int height = (int) StrictGeomUtility.toExternalValue(content.getHeight());

    if (width == 0 || height == 0) {
        LogicalPageDrawable.logger.debug("Error: Image area is empty: " + content);
        return false;
    }

    WaitingImageObserver obs = new WaitingImageObserver(image);
    obs.waitImageLoaded();
    final int imageWidth = image.getWidth(obs);
    final int imageHeight = image.getHeight(obs);
    if (imageWidth < 1 || imageHeight < 1) {
        return false;
    }

    final Rectangle2D.Double drawAreaBounds = new Rectangle2D.Double(x, y, width, height);
    final AffineTransform scaleTransform;

    final Graphics2D g2;
    if (shouldScale == false) {
        double deviceScaleFactor = 1;
        final double devResolution = metaData.getNumericFeatureValue(OutputProcessorFeature.DEVICE_RESOLUTION);
        if (metaData.isFeatureSupported(OutputProcessorFeature.IMAGE_RESOLUTION_MAPPING)) {
            if (devResolution != 72.0 && devResolution > 0) {
                // Need to scale the device to its native resolution before attempting to draw the image..
                deviceScaleFactor = (72.0 / devResolution);
            }
        }

        final int clipWidth = Math.min(width, (int) Math.ceil(deviceScaleFactor * imageWidth));
        final int clipHeight = Math.min(height, (int) Math.ceil(deviceScaleFactor * imageHeight));
        final ElementAlignment horizontalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.ALIGNMENT);
        final ElementAlignment verticalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.VALIGNMENT);
        final int alignmentX = (int) RenderUtility.computeHorizontalAlignment(horizontalAlignment, width,
                clipWidth);
        final int alignmentY = (int) RenderUtility.computeVerticalAlignment(verticalAlignment, height,
                clipHeight);

        g2 = (Graphics2D) getGraphics().create();
        g2.clip(drawAreaBounds);
        g2.translate(x, y);
        g2.translate(alignmentX, alignmentY);
        g2.clip(new Rectangle2D.Float(0, 0, clipWidth, clipHeight));
        g2.scale(deviceScaleFactor, deviceScaleFactor);

        scaleTransform = null;
    } else {
        g2 = (Graphics2D) getGraphics().create();
        g2.clip(drawAreaBounds);
        g2.translate(x, y);
        g2.clip(new Rectangle2D.Float(0, 0, width, height));

        final double scaleX;
        final double scaleY;

        final boolean keepAspectRatio = layoutContext
                .getBooleanStyleProperty(ElementStyleKeys.KEEP_ASPECT_RATIO);
        if (keepAspectRatio) {
            final double scaleFactor = Math.min(width / (double) imageWidth, height / (double) imageHeight);
            scaleX = scaleFactor;
            scaleY = scaleFactor;
        } else {
            scaleX = width / (double) imageWidth;
            scaleY = height / (double) imageHeight;
        }

        final int clipWidth = (int) (scaleX * imageWidth);
        final int clipHeight = (int) (scaleY * imageHeight);

        final ElementAlignment horizontalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.ALIGNMENT);
        final ElementAlignment verticalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.VALIGNMENT);
        final int alignmentX = (int) RenderUtility.computeHorizontalAlignment(horizontalAlignment, width,
                clipWidth);
        final int alignmentY = (int) RenderUtility.computeVerticalAlignment(verticalAlignment, height,
                clipHeight);

        g2.translate(alignmentX, alignmentY);

        final Object contentCached = content.getContent().getContentCached();
        if (contentCached instanceof Image) {
            image = (Image) contentCached;
            scaleTransform = null;
        } else if (metaData.isFeatureSupported(OutputProcessorFeature.PREFER_NATIVE_SCALING) == false) {
            image = RenderUtility.scaleImage(image, clipWidth, clipHeight,
                    RenderingHints.VALUE_INTERPOLATION_BICUBIC, true);
            content.getContent().setContentCached(image);
            obs = new WaitingImageObserver(image);
            obs.waitImageLoaded();
            scaleTransform = null;
        } else {
            scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
        }
    }

    while (g2.drawImage(image, scaleTransform, obs) == false) {
        obs.waitImageLoaded();
        if (obs.isError()) {
            LogicalPageDrawable.logger.warn("Error while loading the image during the rendering.");
            break;
        }
    }

    g2.dispose();
    return true;
}

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

protected boolean drawImage(final RenderableReplacedContentBox content, final Image image,
        final com.lowagie.text.Image itextImage) {
    final StyleSheet layoutContext = content.getStyleSheet();
    final boolean shouldScale = layoutContext.getBooleanStyleProperty(ElementStyleKeys.SCALE);

    final int x = (int) StrictGeomUtility.toExternalValue(content.getX());
    final int y = (int) StrictGeomUtility.toExternalValue(content.getY());
    final int width = (int) StrictGeomUtility.toExternalValue(content.getWidth());
    final int height = (int) StrictGeomUtility.toExternalValue(content.getHeight());

    if (width == 0 || height == 0) {
        PdfLogicalPageDrawable.logger.debug("Error: Image area is empty: " + content);
        return false;
    }//from w ww . j a  v a2  s.  c o  m

    final WaitingImageObserver obs = new WaitingImageObserver(image);
    obs.waitImageLoaded();
    final int imageWidth = image.getWidth(obs);
    final int imageHeight = image.getHeight(obs);
    if (imageWidth < 1 || imageHeight < 1) {
        return false;
    }

    final Rectangle2D.Double drawAreaBounds = new Rectangle2D.Double(x, y, width, height);
    final AffineTransform scaleTransform;

    final Graphics2D g2;
    if (shouldScale == false) {
        double deviceScaleFactor = 1;
        final double devResolution = getMetaData()
                .getNumericFeatureValue(OutputProcessorFeature.DEVICE_RESOLUTION);
        if (getMetaData().isFeatureSupported(OutputProcessorFeature.IMAGE_RESOLUTION_MAPPING)) {
            if (devResolution != 72.0 && devResolution > 0) {
                // Need to scale the device to its native resolution before attempting to draw the image..
                deviceScaleFactor = (72.0 / devResolution);
            }
        }

        final int clipWidth = Math.min(width, (int) Math.ceil(deviceScaleFactor * imageWidth));
        final int clipHeight = Math.min(height, (int) Math.ceil(deviceScaleFactor * imageHeight));
        final ElementAlignment horizontalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.ALIGNMENT);
        final ElementAlignment verticalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.VALIGNMENT);
        final int alignmentX = (int) RenderUtility.computeHorizontalAlignment(horizontalAlignment, width,
                clipWidth);
        final int alignmentY = (int) RenderUtility.computeVerticalAlignment(verticalAlignment, height,
                clipHeight);

        g2 = (Graphics2D) getGraphics().create();
        g2.clip(drawAreaBounds);
        g2.translate(x, y);
        g2.translate(alignmentX, alignmentY);
        g2.clip(new Rectangle2D.Float(0, 0, clipWidth, clipHeight));
        g2.scale(deviceScaleFactor, deviceScaleFactor);

        scaleTransform = null;
    } else {
        g2 = (Graphics2D) getGraphics().create();
        g2.clip(drawAreaBounds);
        g2.translate(x, y);
        g2.clip(new Rectangle2D.Float(0, 0, width, height));

        final double scaleX;
        final double scaleY;

        final boolean keepAspectRatio = layoutContext
                .getBooleanStyleProperty(ElementStyleKeys.KEEP_ASPECT_RATIO);
        if (keepAspectRatio) {
            final double scaleFactor = Math.min(width / (double) imageWidth, height / (double) imageHeight);
            scaleX = scaleFactor;
            scaleY = scaleFactor;
        } else {
            scaleX = width / (double) imageWidth;
            scaleY = height / (double) imageHeight;
        }

        final int clipWidth = (int) (scaleX * imageWidth);
        final int clipHeight = (int) (scaleY * imageHeight);

        final ElementAlignment horizontalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.ALIGNMENT);
        final ElementAlignment verticalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.VALIGNMENT);
        final int alignmentX = (int) RenderUtility.computeHorizontalAlignment(horizontalAlignment, width,
                clipWidth);
        final int alignmentY = (int) RenderUtility.computeVerticalAlignment(verticalAlignment, height,
                clipHeight);

        g2.translate(alignmentX, alignmentY);
        scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
    }

    final PdfGraphics2D pdfGraphics2D = (PdfGraphics2D) g2;
    pdfGraphics2D.drawPdfImage(itextImage, image, scaleTransform, null);
    g2.dispose();
    return true;
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.table.xls.helper.ExcelImageHandler.java

private int clipAndEncodeImage(final Image image, final long width, final long height,
        final double deviceScaleFactor) throws UnsupportedEncoderException, IOException {
    final int imageWidth = (int) StrictGeomUtility.toExternalValue(width);
    final int imageHeight = (int) StrictGeomUtility.toExternalValue(height);
    // first clip.
    final BufferedImage bi = ImageUtils.createTransparentImage(imageWidth, imageHeight);
    final Graphics2D graphics = (Graphics2D) bi.getGraphics();
    graphics.scale(deviceScaleFactor, deviceScaleFactor);

    if (image instanceof BufferedImage) {
        if (graphics.drawImage(image, null, null) == false) {
            logger.debug("Failed to render the image. This should not happen for BufferedImages"); // NON-NLS
        }/*from w ww  . j  av a 2 s.c om*/
    } else {
        final WaitingImageObserver obs = new WaitingImageObserver(image);
        obs.waitImageLoaded();

        while (graphics.drawImage(image, null, obs) == false) {
            obs.waitImageLoaded();
            if (obs.isError()) {
                logger.warn("Error while loading the image during the rendering."); // NON-NLS
                break;
            }
        }
    }

    graphics.dispose();
    final byte[] data = RenderUtility.encodeImage(bi);
    return printerBase.getWorkbook().addPicture(data, Workbook.PICTURE_TYPE_PNG);
}

From source file:org.pentaho.reporting.engine.classic.extensions.modules.sbarcodes.BarcodeWrapper.java

public void draw(final Graphics2D g2, final Rectangle2D bounds) {
    final Graphics2D gr2 = (Graphics2D) g2.create();
    try {//w  ww  . j  a v a  2  s .c o  m
        gr2.clip(bounds);
        if (scale) {
            final Dimension size = barcode.getPreferredSize();
            final double horzScale = bounds.getWidth() / size.getWidth();
            final double vertScale = bounds.getHeight() / size.getHeight();
            if (keepAspectRatio) {
                final double scale = Math.min(horzScale, vertScale);
                gr2.scale(scale, scale);
            } else {
                gr2.scale(horzScale, vertScale);
            }
        }
        barcode.draw(gr2, (int) bounds.getX(), (int) bounds.getY());
    } catch (OutputException e) {
        logger.error("Unable to draw barcode element", e);
    } finally {
        gr2.dispose();
    }

}

From source file:tufts.vue.LWComponent.java

/** transform relative to the child after already being transformed relative to the parent */
protected void transformDownG(final Graphics2D a) {
    if (mTemporaryTransform != null) {
        a.transform(mTemporaryTransform);
    } else {/*ww w  .  j a  va2  s .  co m*/
        a.translate(this.x, this.y);
        if (this.scale != 1)
            a.scale(this.scale, this.scale);
    }
}