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

/** Draw the example */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;
    // Paint the entire background using a GradientPaint.
    // The background color varies diagonally from deep red to pale blue
    g.setPaint(new GradientPaint(0, 0, new Color(150, 0, 0), WIDTH, HEIGHT, new Color(200, 200, 255)));
    g.fillRect(0, 0, WIDTH, HEIGHT); // fill the background

    // Use a different GradientPaint to draw a box.
    // This one alternates between deep opaque green and transparent green.
    // Note: the 4th arg to Color() constructor specifies color opacity
    g.setPaint(new GradientPaint(0, 0, new Color(0, 150, 0), 20, 20, new Color(0, 150, 0, 0), true));
    g.setStroke(new BasicStroke(15)); // use wide lines
    g.drawRect(25, 25, WIDTH - 50, HEIGHT - 50); // draw the box

    // The glyphs of fonts can be used as Shape objects, which enables
    // us to use Java2D techniques with letters Just as we would with
    // any other shape. Here we get some letter shapes to draw.
    Font font = new Font("Serif", Font.BOLD, 10); // a basic font
    Font bigfont = // a scaled up version
            font.deriveFont(AffineTransform.getScaleInstance(30.0, 30.0));
    GlyphVector gv = bigfont.createGlyphVector(g.getFontRenderContext(), "JAV");
    Shape jshape = gv.getGlyphOutline(0); // Shape of letter J
    Shape ashape = gv.getGlyphOutline(1); // Shape of letter A
    Shape vshape = gv.getGlyphOutline(2); // Shape of letter V

    // We're going to outline the letters with a 5-pixel wide line
    g.setStroke(new BasicStroke(5.0f));

    // We're going to fake shadows for the letters using the
    // following Paint and AffineTransform objects
    Paint shadowPaint = new Color(0, 0, 0, 100); // Translucent black
    AffineTransform shadowTransform = AffineTransform.getShearInstance(-1.0, 0.0); // Shear to the right
    shadowTransform.scale(1.0, 0.5); // Scale height by 1/2

    // Move to the baseline of our first letter
    g.translate(65, 270);

    // Draw the shadow of the J shape
    g.setPaint(shadowPaint);//  www  .  j  ava 2  s .c om
    g.translate(15, 20); // Compensate for the descender of the J
    // transform the J into the shape of its shadow, and fill it
    g.fill(shadowTransform.createTransformedShape(jshape));
    g.translate(-15, -20); // Undo the translation above

    // Now fill the J shape with a solid (and opaque) color
    g.setPaint(Color.blue); // Fill with solid, opaque blue
    g.fill(jshape); // Fill the shape
    g.setPaint(Color.black); // Switch to solid black
    g.draw(jshape); // And draw the outline of the J

    // Now draw the A shadow
    g.translate(75, 0); // Move to the right
    g.setPaint(shadowPaint); // Set shadow color
    g.fill(shadowTransform.createTransformedShape(ashape)); // draw shadow

    // Draw the A shape using a solid transparent color
    g.setPaint(new Color(0, 255, 0, 125)); // Transparent green as paint
    g.fill(ashape); // Fill the shape
    g.setPaint(Color.black); // Switch to solid back
    g.draw(ashape); // Draw the outline

    // Move to the right and draw the shadow of the letter V
    g.translate(175, 0);
    g.setPaint(shadowPaint);
    g.fill(shadowTransform.createTransformedShape(vshape));

    // We're going to fill the next letter using a TexturePaint, which
    // repeatedly tiles an image. The first step is to obtain the image.
    // We could load it from an image file, but here we create it
    // ourselves by drawing a into an off-screen image. Note that we use
    // a GradientPaint to fill the off-screen image, so the fill pattern
    // combines features of both Paint classes.
    BufferedImage tile = // Create an image
            new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB);
    Graphics2D tg = tile.createGraphics(); // Get its Graphics for drawing
    tg.setColor(Color.pink);
    tg.fillRect(0, 0, 50, 50); // Fill tile background with pink
    tg.setPaint(new GradientPaint(40, 0, Color.green, // diagonal gradient
            0, 40, Color.gray)); // green to gray
    tg.fillOval(5, 5, 40, 40); // Draw a circle with this gradient

    // Use this new tile to create a TexturePaint and fill the letter V
    g.setPaint(new TexturePaint(tile, new Rectangle(0, 0, 50, 50)));
    g.fill(vshape); // Fill letter shape
    g.setPaint(Color.black); // Switch to solid black
    g.draw(vshape); // Draw outline of letter

    // Move to the right and draw the shadow of the final A
    g.translate(160, 0);
    g.setPaint(shadowPaint);
    g.fill(shadowTransform.createTransformedShape(ashape));

    g.fill(ashape); // Fill letter A
    g.setPaint(Color.black); // Revert to solid black
    g.draw(ashape); // Draw the outline of the A
}

From source file:forseti.JUtil.java

public static synchronized Image generarImagenMensaje(String mensaje, String nombreFuente, int tamanioFuente) {
    Frame f = new Frame();
    f.addNotify();/* w  ww.jav a 2s .c om*/
    GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
    env.getAvailableFontFamilyNames();
    Font fuente = new Font(nombreFuente, Font.PLAIN, tamanioFuente);
    FontMetrics medidas = f.getFontMetrics(fuente);
    int anchoMensaje = medidas.stringWidth(mensaje);
    int lineaBaseX = anchoMensaje / 10;
    int ancho = anchoMensaje + 2 * (lineaBaseX + tamanioFuente);
    int alto = tamanioFuente * 7 / 2;
    int lineaBaseY = alto * 8 / 10;
    Image imagenMensaje = f.createImage(ancho, alto);
    Graphics2D g2d = (Graphics2D) imagenMensaje.getGraphics();
    g2d.setFont(fuente);
    g2d.translate(lineaBaseX, lineaBaseY);
    g2d.setPaint(Color.lightGray);
    AffineTransform origTransform = g2d.getTransform();
    g2d.shear(-0.95, 0);
    g2d.scale(1, 3);
    g2d.drawString(mensaje, 0, 0);
    g2d.setTransform(origTransform);
    g2d.setPaint(Color.black);
    g2d.drawString(mensaje, 0, 0);

    return (imagenMensaje);
}

From source file:spinworld.gui.RadarPlot.java

private void drawTicks(Graphics2D g2, Rectangle2D radarArea, double axisAngle, int cat) {
    double[] ticks = { 0.5d, 1d };
    for (int i = 0; i < ticks.length; i++) {
        double tick = ticks[i];
        Point2D middlePoint = getWebPoint(radarArea, axisAngle, tick);
        double xt = middlePoint.getX();
        double yt = middlePoint.getY();
        double angrad = Math.toRadians(-axisAngle);
        g2.translate(xt, yt);
        g2.rotate(angrad);/*from  w ww. j  av  a 2  s.  com*/
        g2.drawLine(0, (int) -TICK_MARK_LENGTH / 2, 0, (int) TICK_MARK_LENGTH / 2);
        g2.rotate(-angrad);
        g2.translate(-xt, -yt);
        drawTickLabel(g2, radarArea, middlePoint, axisAngle, cat, tick);
    }
}

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

protected void paintComponent(final Graphics g) {
    if (fpsCalculator.isActive()) {
        fpsCalculator.tick();//from   w w  w. ja  va 2  s.c  om
    }

    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.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  www .  j  av a2 s. c  om*/

    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:savant.view.swing.GraphPane.java

public boolean render(Graphics2D g2, Range xRange, Range yRange) {
    LOG.trace("GraphPane.render(g2, " + xRange + ", " + yRange + ")");
    double oldUnitHeight = unitHeight;
    int oldYMax = yMax;

    // Paint a gradient from top to bottom
    GradientPaint gp0 = new GradientPaint(0, 0, ColourSettings.getColor(ColourKey.GRAPH_PANE_BACKGROUND_TOP), 0,
            getHeight(), ColourSettings.getColor(ColourKey.GRAPH_PANE_BACKGROUND_BOTTOM));
    g2.setPaint(gp0);//from  w  w  w  .  j  av  a2  s .  c o m
    g2.fillRect(0, 0, getWidth(), getHeight());

    GraphPaneController gpc = GraphPaneController.getInstance();
    LocationController lc = LocationController.getInstance();
    JScrollBar scroller = getVerticalScrollBar();

    if (gpc.isPanning() && !isLocked()) {

        double fromX = transformXPos(gpc.getMouseClickPosition());
        double toX = transformXPos(gpc.getMouseReleasePosition());
        g2.translate(toX - fromX, 0);
    }

    // Deal with the progress-bar.
    if (tracks == null) {
        parentFrame.updateProgress();
        return false;
    } else {
        for (Track t : tracks) {
            if (t.getRenderer().isWaitingForData()) {
                String progressMsg = (String) t.getRenderer().getInstruction(DrawingInstruction.PROGRESS);
                setPreferredSize(new Dimension(getWidth(), 0));
                showProgress(progressMsg, -1.0);
                return false;
            }
        }
    }
    if (progressPanel != null) {
        remove(progressPanel);
        progressPanel = null;
    }

    int minYRange = Integer.MAX_VALUE;
    int maxYRange = Integer.MIN_VALUE;
    AxisType bestYAxis = AxisType.NONE;
    for (Track t : tracks) {

        // ask renderers for extra info on range; consolidate to maximum Y range
        AxisRange axisRange = (AxisRange) t.getRenderer().getInstruction(DrawingInstruction.AXIS_RANGE);

        if (axisRange != null) {
            int axisYMin = axisRange.getYMin();
            int axisYMax = axisRange.getYMax();
            if (axisYMin < minYRange) {
                minYRange = axisYMin;
            }
            if (axisYMax > maxYRange) {
                maxYRange = axisYMax;
            }
        }

        // Ask renderers if they want horizontal grid-lines; if any say yes, draw them.
        switch (t.getYAxisType(t.getResolution(xRange))) {
        case INTEGER_GRIDLESS:
            if (bestYAxis == AxisType.NONE) {
                bestYAxis = AxisType.INTEGER_GRIDLESS;
            }
            break;
        case INTEGER:
            if (bestYAxis != AxisType.REAL) {
                bestYAxis = AxisType.INTEGER;
            }
            break;
        case REAL:
            bestYAxis = AxisType.REAL;
            break;
        }
    }

    setXAxisType(tracks[0].getXAxisType(tracks[0].getResolution(xRange)));
    setXRange(xRange);
    setYAxisType(bestYAxis);
    Range consolidatedYRange = new Range(minYRange, maxYRange);

    setYRange(consolidatedYRange);
    consolidatedYRange = new Range(yMin, yMax);

    DrawingMode currentMode = tracks[0].getDrawingMode();

    boolean sameRange = (prevRange != null && xRange.equals(prevRange));
    if (!sameRange) {
        PopupPanel.hidePopup();
    }
    boolean sameMode = currentMode == prevMode;
    boolean sameSize = prevSize != null && getSize().equals(prevSize)
            && parentFrame.getFrameLandscape().getWidth() == oldWidth
            && parentFrame.getFrameLandscape().getHeight() == oldHeight;
    boolean sameRef = prevRef != null && lc.getReferenceName().equals(prevRef);
    boolean withinScrollBounds = bufferedImage != null && scroller.getValue() >= getOffset()
            && scroller.getValue() < getOffset() + getViewportHeight() * 2;

    //bufferedImage stores the current graphic for future use. If nothing
    //has changed in the track since the last render, bufferedImage will
    //be used to redraw the current view. This method allows for fast repaints
    //on tracks where nothing has changed (panning, selection, plumbline,...)

    //if nothing has changed draw buffered image
    if (sameRange && sameMode && sameSize && sameRef && !renderRequired && withinScrollBounds) {
        g2.drawImage(bufferedImage, 0, getOffset(), this);
        renderCurrentSelected(g2);

        //force unitHeight from last render
        unitHeight = oldUnitHeight;
        yMax = oldYMax;

    } else {
        // Otherwise prepare for new render.
        renderRequired = false;

        int h = getHeight();
        if (!forcedHeight) {
            h = Math.min(h, getViewportHeight() * 3);
        }
        LOG.debug("Requesting " + getWidth() + "\u00D7" + h + " bufferedImage.");
        bufferedImage = new BufferedImage(getWidth(), h, BufferedImage.TYPE_INT_RGB);
        if (bufferedImage.getHeight() == getHeight()) {
            setOffset(0);
        } else {
            setOffset(scroller.getValue() - getViewportHeight());
        }
        LOG.debug("Rendering fresh " + bufferedImage.getWidth() + "\u00D7" + bufferedImage.getHeight()
                + " bufferedImage at (0, " + getOffset() + ")");

        Graphics2D g3 = bufferedImage.createGraphics();
        g3.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        prevRange = xRange;
        prevSize = getSize();
        prevMode = tracks[0].getDrawingMode();
        prevRef = lc.getReferenceName();

        renderBackground(g3, xAxisType == AxisType.INTEGER || xAxisType == AxisType.REAL,
                yAxisType == AxisType.INTEGER || yAxisType == AxisType.REAL);

        // Call the actual render() methods.
        boolean nothingRendered = true;
        String message = null;
        int priority = -1;

        for (Track t : tracks) {
            // Change renderers' drawing instructions to reflect consolidated YRange
            AxisRange axes = (AxisRange) t.getRenderer().getInstruction(DrawingInstruction.AXIS_RANGE);

            if (axes == null) {
                axes = new AxisRange(xRange, consolidatedYRange);
            } else {
                axes = new AxisRange(axes.getXRange(), consolidatedYRange);
            }

            //System.out.println("Consolidated y range for " + t.getName() + " is " + consolidatedYRange);
            t.getRenderer().addInstruction(DrawingInstruction.AXIS_RANGE, axes);

            try {
                t.getRenderer().render(g3, this);
                nothingRendered = false;
            } catch (RenderingException rx) {
                if (rx.getPriority() > priority) {
                    // If we have more than one message with the same priority, the first one will end up being drawn.
                    message = rx.getMessage();
                    priority = rx.getPriority();
                }
            } catch (Throwable x) {
                // Renderer itself threw an exception.
                LOG.error("Error rendering " + t, x);
                message = MiscUtils.getMessage(x);
                priority = RenderingException.ERROR_PRIORITY;
            }
        }
        if (nothingRendered && message != null) {
            setPreferredSize(new Dimension(getWidth(), 0));
            revalidate();
            drawMessage(g3, message);
        }

        updateYMax();

        // If a change has occured that affects scrollbar...
        if (paneResize) {
            paneResize = false;

            // Change size of current frame
            if (getHeight() != newHeight) {
                Dimension newSize = new Dimension(getWidth(), newHeight);
                setPreferredSize(newSize);
                setSize(newSize);
                parentFrame.validate(); // Ensures that scroller.getMaximum() is up to date.

                // If pane is resized, scrolling always starts at the bottom.  The only place
                // where looks wrong is when we have a continuous track with negative values.
                scroller.setValue(scroller.getMaximum());
                repaint();
                return false;
            }
        } else if (oldViewHeight != -1 && oldViewHeight != getViewportHeight()) {
            int newViewHeight = getViewportHeight();
            int oldScroll = scroller.getValue();
            scroller.setValue(oldScroll + (oldViewHeight - newViewHeight));
            oldViewHeight = newViewHeight;
        }
        oldWidth = parentFrame.getFrameLandscape().getWidth();
        oldHeight = parentFrame.getFrameLandscape().getHeight();

        g2.drawImage(bufferedImage, 0, getOffset(), this);
        fireExportEvent(xRange, bufferedImage);

        renderCurrentSelected(g2);
    }
    return true;
}

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

protected boolean drawDrawable(final RenderableReplacedContentBox content, final Graphics2D g2,
        final DrawableWrapper d) {
    final double x = StrictGeomUtility.toExternalValue(content.getX());
    final double y = StrictGeomUtility.toExternalValue(content.getY());
    final double width = StrictGeomUtility.toExternalValue(content.getWidth());
    final double height = StrictGeomUtility.toExternalValue(content.getHeight());

    if ((width < 0 || height < 0) || (width == 0 && height == 0)) {
        return false;
    }//from  www  . j  a  v  a  2s  .  com

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

    final StyleSheet styleSheet = content.getStyleSheet();
    final Object attribute = styleSheet.getStyleProperty(ElementStyleKeys.ANTI_ALIASING);
    if (attribute != null) {
        if (Boolean.TRUE.equals(attribute)) {
            clone.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        } else if (Boolean.FALSE.equals(attribute)) {
            clone.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
        }

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

    if (strictClipping == false) {
        final double extraPadding;
        final Object o = styleSheet.getStyleProperty(ElementStyleKeys.STROKE);
        if (o instanceof BasicStroke) {
            final BasicStroke stroke = (BasicStroke) o;
            extraPadding = stroke.getLineWidth() / 2.0;
        } else {
            extraPadding = 0.5;
        }

        final Rectangle2D.Double clipBounds = new Rectangle2D.Double(x - extraPadding, y - extraPadding,
                width + 2 * extraPadding, height + 2 * extraPadding);

        clone.clip(clipBounds);
        clone.translate(x, y);
    } else {
        final Rectangle2D.Double clipBounds = new Rectangle2D.Double(x, y, width + 1, height + 1);

        clone.clip(clipBounds);
        clone.translate(x, y);
    }
    configureGraphics(styleSheet, clone);
    configureStroke(styleSheet, clone);
    final Rectangle2D.Double bounds = new Rectangle2D.Double(0, 0, width, height);
    d.draw(clone, bounds);
    clone.dispose();
    return true;
}

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

/**
 * @param content/*from   w  w w .  j  a  va  2  s  .  co m*/
 * @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:com.rapidminer.gui.plotter.charts.AbstractChartPanel.java

/**
 * Paints the component by drawing the chart to fill the entire component, but allowing for the
 * insets (which will be non-zero if a border has been set for this component). To increase
 * performance (at the expense of memory), an off-screen buffer image can be used.
 * /*from   ww w  .j a  v  a2 s . c o m*/
 * @param g
 *            the graphics device for drawing on.
 */

@Override
public void paintComponent(Graphics g) {
    if (this.chart == null) {
        return;
    }
    Graphics2D g2 = (Graphics2D) g.create();

    // first determine the size of the chart rendering area...
    Dimension size = getSize();
    Insets insets = getInsets();
    Rectangle2D available = new Rectangle2D.Double(insets.left, insets.top,
            size.getWidth() - insets.left - insets.right, size.getHeight() - insets.top - insets.bottom);

    // work out if scaling is required...
    boolean scale = false;
    double drawWidth = available.getWidth();
    double drawHeight = available.getHeight();
    this.scaleX = 1.0;
    this.scaleY = 1.0;

    if (drawWidth < this.minimumDrawWidth) {
        this.scaleX = drawWidth / this.minimumDrawWidth;
        drawWidth = this.minimumDrawWidth;
        scale = true;
    } else if (drawWidth > this.maximumDrawWidth) {
        this.scaleX = drawWidth / this.maximumDrawWidth;
        drawWidth = this.maximumDrawWidth;
        scale = true;
    }

    if (drawHeight < this.minimumDrawHeight) {
        this.scaleY = drawHeight / this.minimumDrawHeight;
        drawHeight = this.minimumDrawHeight;
        scale = true;
    } else if (drawHeight > this.maximumDrawHeight) {
        this.scaleY = drawHeight / this.maximumDrawHeight;
        drawHeight = this.maximumDrawHeight;
        scale = true;
    }

    Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth, drawHeight);
    // redrawing the chart every time...

    AffineTransform saved = g2.getTransform();
    g2.translate(insets.left, insets.top);
    if (scale) {
        AffineTransform st = AffineTransform.getScaleInstance(this.scaleX, this.scaleY);
        g2.transform(st);
    }
    this.chart.draw(g2, chartArea, this.anchor, this.info);
    g2.setTransform(saved);

    Iterator<Overlay> iterator = this.overlays.iterator();
    while (iterator.hasNext()) {
        Overlay overlay = iterator.next();
        overlay.paintOverlay(g2, this);
    }

    // redraw the zoom rectangle (if present) - if useBuffer is false,
    // we use XOR so we can XOR the rectangle away again without redrawing
    // the chart
    drawSelectionRectangle(g2);

    g2.dispose();

    this.anchor = null;
    this.verticalTraceLine = null;
    this.horizontalTraceLine = null;

}

From source file:net.sourceforge.processdash.ui.web.reports.RadarPlot.java

protected void drawRadar(Graphics2D g2, Rectangle2D plotArea, PlotRenderingInfo info, int pieIndex,
        PieDataset data) {/*from  w  ww  . j  a  va2 s. c  o m*/

    // adjust the plot area by the interior spacing value
    double gapHorizontal = plotArea.getWidth() * this.interiorGap;
    double gapVertical = plotArea.getHeight() * this.interiorGap;
    double radarX = plotArea.getX() + gapHorizontal / 2;
    double radarY = plotArea.getY() + gapVertical / 2;
    double radarW = plotArea.getWidth() - gapHorizontal;
    double radarH = plotArea.getHeight() - gapVertical;

    // make the radar area a square if the radar chart is to be circular...
    // NOTE that non-circular radar charts are not currently supported.
    if (true) { //circular) {
        double min = Math.min(radarW, radarH) / 2;
        radarX = (radarX + radarX + radarW) / 2 - min;
        radarY = (radarY + radarY + radarH) / 2 - min;
        radarW = 2 * min;
        radarH = 2 * min;
    }

    double radius = radarW / 2;
    double centerX = radarX + radarW / 2;
    double centerY = radarY + radarH / 2;

    Rectangle2D radarArea = new Rectangle2D.Double(radarX, radarY, radarW, radarH);

    // plot the data (unless the dataset is null)...
    if ((data != null) && (data.getKeys().size() > 0)) {

        // get a list of categories...
        List keys = data.getKeys();
        int numAxes = keys.size();

        // draw each of the axes on the radar chart, and register
        // the shape of the radar line.

        double multiplier = 1.0;
        GeneralPath lineShape = new GeneralPath(GeneralPath.WIND_NON_ZERO, numAxes + 1);
        GeneralPath gridShape = new GeneralPath(GeneralPath.WIND_NON_ZERO, numAxes + 1);

        int axisNumber = -1;
        Iterator iterator = keys.iterator();
        while (iterator.hasNext()) {
            Comparable currentKey = (Comparable) iterator.next();
            axisNumber++;
            Number dataValue = data.getValue(currentKey);

            double value = (dataValue != null ? dataValue.doubleValue() : 0);
            if (value > 1 || Double.isNaN(value) || Double.isInfinite(value))
                value = 1.0;
            if (value < 0)
                value = 0.0;
            multiplier *= value;

            double angle = 2 * Math.PI * axisNumber / numAxes;
            double deltaX = Math.sin(angle) * radius;
            double deltaY = -Math.cos(angle) * radius;

            // draw the spoke
            g2.setPaint(axisPaint);
            g2.setStroke(axisStroke);
            Line2D line = new Line2D.Double(centerX, centerY, centerX + deltaX, centerY + deltaY);
            g2.draw(line);

            // register the grid line and the shape line
            if (axisNumber == 0) {
                gridShape.moveTo((float) deltaX, (float) deltaY);
                lineShape.moveTo((float) (deltaX * value), (float) (deltaY * value));
            } else {
                gridShape.lineTo((float) deltaX, (float) deltaY);
                lineShape.lineTo((float) (deltaX * value), (float) (deltaY * value));
            }

            if (showAxisLabels) {
                // draw the label
                double labelX = centerX + deltaX * (1 + axisLabelGap);
                double labelY = centerY + deltaY * (1 + axisLabelGap);
                String label = currentKey.toString();
                drawLabel(g2, radarArea, label, axisNumber, labelX, labelY);
            }

        }
        gridShape.closePath();
        lineShape.closePath();

        // draw five gray concentric gridlines
        g2.translate(centerX, centerY);
        g2.setPaint(gridLinePaint);
        g2.setStroke(gridLineStroke);
        for (int i = 5; i > 0; i--) {
            Shape scaledGrid = gridShape
                    .createTransformedShape(AffineTransform.getScaleInstance(i / 5.0, i / 5.0));
            g2.draw(scaledGrid);
        }

        // get the color for the plot shape.
        Paint dataPaint = plotLinePaint;
        if (dataPaint == ADAPTIVE_COLORING) {
            //multiplier = Math.exp(Math.log(multiplier) * 2 / numAxes);
            dataPaint = getMultiplierColor((float) multiplier);
        }

        // compute a slightly transparent version of the plot color for
        // the fill.
        Paint dataFill = null;
        if (dataPaint instanceof Color && getForegroundAlpha() != 1.0)
            dataFill = new Color(((Color) dataPaint).getRed() / 255f, ((Color) dataPaint).getGreen() / 255f,
                    ((Color) dataPaint).getBlue() / 255f, getForegroundAlpha());
        else
            dataFill = dataPaint;

        // draw the plot shape.  First fill with a parially
        // transparent color, then stroke with the opaque color.
        g2.setPaint(dataFill);
        g2.fill(lineShape);
        g2.setPaint(dataPaint);
        g2.setStroke(plotLineStroke);
        g2.draw(lineShape);

        // cleanup the graphics context.
        g2.translate(-centerX, -centerY);
    }
}