Example usage for java.awt Graphics2D setClip

List of usage examples for java.awt Graphics2D setClip

Introduction

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

Prototype

public abstract void setClip(Shape clip);

Source Link

Document

Sets the current clipping area to an arbitrary clip shape.

Usage

From source file:net.sf.maltcms.common.charts.api.overlay.SelectionOverlay.java

private void drawEntity(Shape entity, Graphics2D g2, Color fill, ChartPanel chartPanel, boolean scale) {
    if (entity != null) {
        Shape savedClip = g2.getClip();
        Rectangle2D dataArea = chartPanel.getScreenDataArea();
        Color c = g2.getColor();/*  w w  w . j  a v  a2  s  . com*/
        Composite comp = g2.getComposite();
        g2.clip(dataArea);
        g2.setColor(fill);
        AffineTransform originalTransform = g2.getTransform();
        Shape transformed = entity;
        if (scale) {
            transformed = scaleAtOrigin(entity, hoverScaleX, hoverScaleY).createTransformedShape(entity);
        }
        transformed = getTranslateInstance(
                entity.getBounds2D().getCenterX() - transformed.getBounds2D().getCenterX(),
                entity.getBounds2D().getCenterY() - transformed.getBounds2D().getCenterY())
                        .createTransformedShape(transformed);
        g2.setComposite(getInstance(AlphaComposite.SRC_OVER, fillAlpha));
        g2.fill(transformed);
        g2.setColor(Color.DARK_GRAY);
        g2.draw(transformed);
        g2.setComposite(comp);
        g2.setColor(c);
        g2.setClip(savedClip);
    }
}

From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.MultiAxesCrosshairOverlay.java

@Override
public void paintOverlay(Graphics2D g2, ChartPanel chartPanel) {
    Shape savedClip = g2.getClip();
    Rectangle2D dataArea = chartPanel.getScreenDataArea();
    g2.clip(dataArea);//  w w w  .j a va  2s . c o m
    JFreeChart chart = chartPanel.getChart();
    XYPlot plot = (XYPlot) chart.getPlot();
    ValueAxis xAxis = plot.getDomainAxis();
    RectangleEdge xAxisEdge = plot.getDomainAxisEdge();
    Iterator iterator = this.getDomainCrosshairs().iterator();
    while (iterator.hasNext()) {
        Crosshair ch = (Crosshair) iterator.next();
        if (ch.isVisible()) {
            double x = ch.getValue();
            double xx = xAxis.valueToJava2D(x, dataArea, xAxisEdge);
            if (plot.getOrientation() == PlotOrientation.VERTICAL) {
                drawVerticalCrosshair(g2, dataArea, xx, ch);
            } else {
                drawHorizontalCrosshair(g2, dataArea, xx, ch);
            }
        }
    }

    int rangeAxisIdx = 0;
    for (ArrayList<Crosshair> crosshairsForRange : rangeCrosshairs) {
        ValueAxis yAxis = plot.getRangeAxis(rangeAxisIdx);
        RectangleEdge yAxisEdge = plot.getRangeAxisEdge(rangeAxisIdx);
        iterator = crosshairsForRange.iterator();
        while (iterator.hasNext()) {
            Crosshair ch = (Crosshair) iterator.next();
            if (ch.isVisible()) {
                double y = ch.getValue();
                double yy = yAxis.valueToJava2D(y, dataArea, yAxisEdge);
                if (plot.getOrientation() == PlotOrientation.VERTICAL) {
                    drawHorizontalCrosshair(g2, dataArea, yy, ch);
                } else {
                    drawVerticalCrosshair(g2, dataArea, yy, ch);
                }
            }
        }
        g2.setClip(savedClip);
        ++rangeAxisIdx;
    }
}

From source file:com.moviejukebox.plugin.DefaultImagePlugin.java

/**
 * Draw rounded corners on the image/*  w  ww . ja v  a 2 s.  c  o m*/
 *
 * @param bi
 * @return
 */
protected BufferedImage drawRoundCorners(BufferedImage bi) {
    BufferedImage newImg = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D newGraphics = newImg.createGraphics();
    newGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    RoundRectangle2D.Double rect = new RoundRectangle2D.Double(0, 0, bi.getWidth(), bi.getHeight(),
            rcqFactor * cornerRadius, rcqFactor * cornerRadius);
    newGraphics.setClip(rect);
    newGraphics.drawImage(bi, 0, 0, null);

    newGraphics.dispose();
    return newImg;
}

From source file:com.siteview.ecc.report.xls.JRXlsExporter.java

protected void exportImage(JRPrintImage element, JRExporterGridCell gridCell, int colIndex, int rowIndex,
        int emptyCols) throws JRException {
    try {/*ww  w  . j a v a2  s . co m*/
        int topPadding = Math.max(element.getLineBox().getTopPadding().intValue(),
                getImageBorderCorrection(element.getLineBox().getTopPen()));
        int leftPadding = Math.max(element.getLineBox().getLeftPadding().intValue(),
                getImageBorderCorrection(element.getLineBox().getLeftPen()));
        int bottomPadding = Math.max(element.getLineBox().getBottomPadding().intValue(),
                getImageBorderCorrection(element.getLineBox().getBottomPen()));
        int rightPadding = Math.max(element.getLineBox().getRightPadding().intValue(),
                getImageBorderCorrection(element.getLineBox().getRightPen()));

        //pngEncoder.setImage( null );

        int availableImageWidth = element.getWidth() - leftPadding - rightPadding;
        availableImageWidth = availableImageWidth < 0 ? 0 : availableImageWidth;

        int availableImageHeight = element.getHeight() - topPadding - bottomPadding;
        availableImageHeight = availableImageHeight < 0 ? 0 : availableImageHeight;

        JRRenderable renderer = element.getRenderer();

        if (renderer != null && availableImageWidth > 0 && availableImageHeight > 0) {
            if (renderer.getType() == JRRenderable.TYPE_IMAGE) {
                // Image renderers are all asked for their image data and dimension at some point.
                // Better to test and replace the renderer now, in case of lazy load error.
                renderer = JRImageRenderer.getOnErrorRendererForImageData(renderer, element.getOnErrorType());
                if (renderer != null) {
                    renderer = JRImageRenderer.getOnErrorRendererForDimension(renderer,
                            element.getOnErrorType());
                }
            }
        } else {
            renderer = null;
        }

        if (renderer != null) {
            int normalWidth = availableImageWidth;
            int normalHeight = availableImageHeight;

            Dimension2D dimension = renderer.getDimension();
            if (dimension != null) {
                normalWidth = (int) dimension.getWidth();
                normalHeight = (int) dimension.getHeight();
            }

            float xalignFactor = 0f;
            switch (element.getHorizontalAlignment()) {
            case JRAlignment.HORIZONTAL_ALIGN_RIGHT: {
                xalignFactor = 1f;
                break;
            }
            case JRAlignment.HORIZONTAL_ALIGN_CENTER: {
                xalignFactor = 0.5f;
                break;
            }
            case JRAlignment.HORIZONTAL_ALIGN_LEFT:
            default: {
                xalignFactor = 0f;
                break;
            }
            }

            float yalignFactor = 0f;
            switch (element.getVerticalAlignment()) {
            case JRAlignment.VERTICAL_ALIGN_BOTTOM: {
                yalignFactor = 1f;
                break;
            }
            case JRAlignment.VERTICAL_ALIGN_MIDDLE: {
                yalignFactor = 0.5f;
                break;
            }
            case JRAlignment.VERTICAL_ALIGN_TOP:
            default: {
                yalignFactor = 0f;
                break;
            }
            }

            BufferedImage bi = new BufferedImage(element.getWidth(), element.getHeight(),
                    BufferedImage.TYPE_INT_ARGB);
            Graphics2D grx = bi.createGraphics();

            switch (element.getScaleImage()) {
            case JRImage.SCALE_IMAGE_CLIP: {
                int xoffset = (int) (xalignFactor * (availableImageWidth - normalWidth));
                int yoffset = (int) (yalignFactor * (availableImageHeight - normalHeight));

                Shape oldClipShape = grx.getClip();

                grx.clip(new Rectangle(leftPadding, topPadding, availableImageWidth, availableImageHeight));

                try {
                    renderer.render(grx, new Rectangle(xoffset + leftPadding, yoffset + topPadding, normalWidth,
                            normalHeight));
                } finally {
                    grx.setClip(oldClipShape);
                }

                break;
            }
            case JRImage.SCALE_IMAGE_FILL_FRAME: {
                renderer.render(grx,
                        new Rectangle(leftPadding, topPadding, availableImageWidth, availableImageHeight));

                break;
            }
            case JRImage.SCALE_IMAGE_RETAIN_SHAPE:
            default: {
                if (element.getHeight() > 0) {
                    double ratio = (double) normalWidth / (double) normalHeight;

                    if (ratio > (double) availableImageWidth / (double) availableImageHeight) {
                        normalWidth = availableImageWidth;
                        normalHeight = (int) (availableImageWidth / ratio);
                    } else {
                        normalWidth = (int) (availableImageHeight * ratio);
                        normalHeight = availableImageHeight;
                    }

                    int xoffset = leftPadding + (int) (xalignFactor * (availableImageWidth - normalWidth));
                    int yoffset = topPadding + (int) (yalignFactor * (availableImageHeight - normalHeight));

                    renderer.render(grx, new Rectangle(xoffset, yoffset, normalWidth, normalHeight));
                }

                break;
            }
            }

            short mode = backgroundMode;
            short backcolor = whiteIndex;
            if (!isIgnoreCellBackground && gridCell.getCellBackcolor() != null) {
                mode = HSSFCellStyle.SOLID_FOREGROUND;
                backcolor = getNearestColor(gridCell.getCellBackcolor()).getIndex();
            }

            short forecolor = getNearestColor(element.getLineBox().getPen().getLineColor()).getIndex();

            if (element.getMode() == JRElement.MODE_OPAQUE) {
                backcolor = getNearestColor(element.getBackcolor()).getIndex();
            }

            HSSFCellStyle cellStyle = getLoadedCellStyle(mode, backcolor, HSSFCellStyle.ALIGN_LEFT,
                    HSSFCellStyle.VERTICAL_TOP, (short) 0,
                    getLoadedFont(getDefaultFont(), forecolor, null, getLocale()), gridCell);

            createMergeRegion(gridCell, colIndex, rowIndex, cellStyle);

            cell = row.createCell(colIndex);
            //            cell.setCellStyle(cellStyle);

            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) colIndex, rowIndex,
                    (short) (colIndex + gridCell.getColSpan()),
                    rowIndex + (isCollapseRowSpan ? 1 : gridCell.getRowSpan()));
            anchor.setAnchorType(2);
            //pngEncoder.setImage(bi);
            //int imgIndex = workbook.addPicture(pngEncoder.pngEncode(), HSSFWorkbook.PICTURE_TYPE_PNG);
            int imgIndex = workbook.addPicture(
                    JRImageLoader.loadImageDataFromAWTImage(bi, JRRenderable.IMAGE_TYPE_PNG),
                    HSSFWorkbook.PICTURE_TYPE_PNG);
            patriarch.createPicture(anchor, imgIndex);
        }
    } catch (Exception ex) {
        throw new JRException("The cell cannot be added", ex);
    } catch (Error err) {
        throw new JRException("The cell cannot be added", err);
    }
}

From source file:peakml.util.jfreechart.FastSpectrumPlot.java

@Override
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState,
        PlotRenderingInfo info) {/*ww  w  .  j a  v a2 s. c o  m*/
    // add the plot area to the info (used amongst other by the axis for zooming)
    if (info != null)
        info.setPlotArea(area);

    // add the insets (if any)
    RectangleInsets insets = getInsets();
    insets.trim(area);

    // draw the axis and add the dataArea to the info (used amongst other by the axis for zooming)
    AxisSpace space = new AxisSpace();
    space = xaxis.reserveSpace(g2, this, area, RectangleEdge.BOTTOM, space);
    space = yaxis.reserveSpace(g2, this, area, RectangleEdge.LEFT, space);

    Rectangle2D dataArea = space.shrink(area, null);
    if (info != null)
        info.setDataArea(dataArea);

    // flood fill the whole area with the background color
    drawBackground(g2, dataArea);

    // draw the axis
    xaxis.draw(g2, dataArea.getMaxY(), area, dataArea, RectangleEdge.BOTTOM, info);
    yaxis.draw(g2, dataArea.getMinX(), area, dataArea, RectangleEdge.LEFT, info);

    // sanity check
    if (dataseries.size() == 0)
        return;

    // clip the draw area
    Shape originalclip = g2.getClip();
    g2.clip(dataArea);

    // draw all the values
    for (Data data : dataseries) {
        int xpos = (int) xaxis.valueToJava2D(data.mass, dataArea, RectangleEdge.BOTTOM);
        int ypos = (int) yaxis.valueToJava2D(data.intensity, dataArea, RectangleEdge.LEFT);
        g2.drawLine(xpos, (int) yaxis.valueToJava2D(0, dataArea, RectangleEdge.LEFT), xpos, ypos);

        // draw the label
        if (data.description != null && data.description.length() != 0) {
            g2.setColor(Color.RED);
            g2.drawLine(xpos + 2, ypos - 2, xpos + 15, ypos - 15);
            g2.setColor(Color.BLACK);
            g2.drawString(data.description, xpos + 17, ypos - 17);
        }
    }

    // reset
    g2.setClip(originalclip);
}

From source file:peakml.util.jfreechart.FastTimePlot.java

@Override
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState,
        PlotRenderingInfo info) {/*from w ww . jav a2 s . co  m*/
    // add the plot area to the info (used amongst other by the axis for zooming)
    if (info != null)
        info.setPlotArea(area);

    // add the insets (if any)
    RectangleInsets insets = getInsets();
    insets.trim(area);

    // draw the axis and add the dataArea to the info (used amongst other by the axis for zooming)
    AxisSpace space = new AxisSpace();
    space = xaxis.reserveSpace(g2, this, area, RectangleEdge.BOTTOM, space);
    space = yaxis.reserveSpace(g2, this, area, RectangleEdge.LEFT, space);

    Rectangle2D dataArea = space.shrink(area, null);
    if (info != null)
        info.setDataArea(dataArea);

    // flood fill the whole area with the background color
    drawBackground(g2, dataArea);

    // draw the axis
    xaxis.draw(g2, dataArea.getMaxY(), area, dataArea, RectangleEdge.BOTTOM, info);
    yaxis.draw(g2, dataArea.getMinX(), area, dataArea, RectangleEdge.LEFT, info);

    // sanity check
    if (dataseries.size() == 0)
        return;

    // clip the draw area
    Shape originalclip = g2.getClip();
    g2.clip(dataArea);

    // draw all the values
    int index = 0;
    for (Data data : dataseries.values()) {
        g2.setColor(new Color(data.color == -1 ? colormap.getColor(index++) : data.color));
        for (int i = 0; i < data.size - 1; ++i) {
            g2.drawLine((int) xaxis.valueToJava2D(data.time[i], dataArea, RectangleEdge.BOTTOM),
                    (int) yaxis.valueToJava2D(data.values[i], dataArea, RectangleEdge.LEFT),
                    (int) xaxis.valueToJava2D(data.time[i + 1], dataArea, RectangleEdge.BOTTOM),
                    (int) yaxis.valueToJava2D(data.values[i + 1], dataArea, RectangleEdge.LEFT));
        }
    }

    // reset
    g2.setClip(originalclip);
}

From source file:net.sf.maltcms.chromaui.charts.overlay.Peak1DHeatmapOverlay.java

/**
 *
 * @param g2// w  w  w .  j av a 2  s . c om
 * @param chartPanel
 */
@Override
public void paintOverlay(Graphics2D g2, ChartPanel chartPanel) {
    if (isVisible()) {
        Shape savedClip = g2.getClip();
        Rectangle2D dataArea = chartPanel.getScreenDataArea();
        g2.clip(dataArea);
        JFreeChart chart = chartPanel.getChart();
        XYPlot plot = (XYPlot) chart.getPlot();
        ValueAxis xAxis = plot.getDomainAxis();
        RectangleEdge xAxisEdge = plot.getDomainAxisEdge();
        ValueAxis yAxis = plot.getRangeAxis();
        RectangleEdge yAxisEdge = plot.getRangeAxisEdge();
        Color c = g2.getColor();
        Color fillColor = peakAnnotations.getColor();
        if (fillColor == null || fillColor.equals(Color.WHITE)
                || fillColor.equals(new Color(255, 255, 255, 0))) {
            Logger.getLogger(getClass().getName())
                    .info("Peak annotation color was null or white, using color from treatment group!");
            fillColor = peakAnnotations.getChromatogram().getTreatmentGroup().getColor();
        }
        g2.setColor(ChartCustomizer.withAlpha(fillColor, 0.5f));
        for (IPeakAnnotationDescriptor descr : peakAnnotations.getMembers()) {
            double x = descr.getApexTime();
            double xx = xAxis.valueToJava2D(x, dataArea, xAxisEdge);
            double width = xAxis.valueToJava2D(1, dataArea, xAxisEdge);
            double mzRange = (descr.getMassValues()[descr.getMassValues().length - 1]
                    - descr.getMassValues()[0]);
            double y = mzRange / 2.0d;
            double yy = yAxis.valueToJava2D(y, dataArea, yAxisEdge);
            double height = yAxis.valueToJava2D(mzRange, dataArea, yAxisEdge);
            AffineTransform at = AffineTransform.getTranslateInstance(xx, yy);
            at.concatenate(AffineTransform.getTranslateInstance(-x, -y));
            Rectangle2D.Double r = new Rectangle2D.Double(xx - (width / 2.0d), yy, width, height);
            g2.fill(at.createTransformedShape(r));
        }
        g2.setColor(c);
        g2.setClip(savedClip);
    }
}

From source file:ucar.unidata.idv.control.chart.TimeSeriesChart.java

/**
 * Draw the sunrise/sunset curves//ww  w  .j  a v  a 2 s  . co m
 *
 * @param g2  the graphics area
 * @param plot   the plot
 * @param dataArea  the date range
 */
private void drawSunriseSunset(Graphics2D g2, XYPlot plot, Rectangle2D dataArea) {
    if (sunriseLocation == null) {
        return;
    }
    DateAxis domainAxis = (DateAxis) plot.getDomainAxis();
    Date startDate = ((DateAxis) domainAxis).getMinimumDate();
    Date endDate = ((DateAxis) domainAxis).getMaximumDate();
    if ((sunriseDates == null) || !Misc.equals(startDate, lastStartDate)
            || !Misc.equals(endDate, lastEndDate)) {
        lastStartDate = startDate;
        lastEndDate = endDate;
        sunriseDates = IdvTimeline.makeSunriseDates(sunriseLocation, startDate, endDate);
    }
    int top = (int) (dataArea.getY());
    int bottom = (int) (dataArea.getY() + dataArea.getHeight());
    int height = bottom - top;
    g2.setColor(Color.yellow);
    Shape originalClip = g2.getClip();
    g2.clip(dataArea);
    for (int i = 0; i < sunriseDates.size(); i += 2) {
        Date d1 = (Date) sunriseDates.get(i + 1);
        Date d2 = (Date) sunriseDates.get(i);
        int x1 = (int) domainAxis.valueToJava2D(d1.getTime(), dataArea, RectangleEdge.BOTTOM);
        int x2 = (int) domainAxis.valueToJava2D(d2.getTime(), dataArea, RectangleEdge.BOTTOM);
        g2.fillRect(x1, top, (x2 - x1), height);
    }
    g2.setClip(originalClip);
}

From source file:org.proteosuite.FastScatterPlot.java

/**
 * Draws the fast scatter plot on a Java 2D graphics device (such as the 
 * screen or a printer)./*from   w  w  w .  j ava  2  s  .c  om*/
 *
 * @param g2  the graphics device.
 * @param area   the area within which the plot (including axis labels)
 *                   should be drawn.
 * @param anchor  the anchor point (<code>null</code> permitted).
 * @param parentState  the state from the parent plot, if there is one.
 * @param info  collects chart drawing information (<code>null</code> 
 *              permitted).
 */
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState,
        PlotRenderingInfo info) {

    // set up info collection...
    if (info != null) {
        info.setPlotArea(area);
    }

    // adjust the drawing area for plot insets (if any)...
    RectangleInsets insets = getInsets();
    insets.trim(area);

    AxisSpace space = new AxisSpace();
    space = this.domainAxis.reserveSpace(g2, this, area, RectangleEdge.BOTTOM, space);
    space = this.rangeAxis.reserveSpace(g2, this, area, RectangleEdge.LEFT, space);
    Rectangle2D dataArea = space.shrink(area, null);

    if (info != null) {
        info.setDataArea(dataArea);
    }

    // draw the plot background and axes...
    drawBackground(g2, dataArea);

    AxisState domainAxisState = null;
    AxisState rangeAxisState = null;
    if (this.domainAxis != null) {
        domainAxisState = this.domainAxis.draw(g2, dataArea.getMaxY(), area, dataArea, RectangleEdge.BOTTOM,
                info);
    }
    if (this.rangeAxis != null) {
        rangeAxisState = this.rangeAxis.draw(g2, dataArea.getMinX(), area, dataArea, RectangleEdge.LEFT, info);
    }
    drawDomainGridlines(g2, dataArea, domainAxisState.getTicks());
    drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks());

    Shape originalClip = g2.getClip();
    Composite originalComposite = g2.getComposite();

    g2.clip(dataArea);
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha()));

    render(g2, dataArea, info, null);

    g2.setClip(originalClip);
    g2.setComposite(originalComposite);
    drawOutline(g2, dataArea);

}

From source file:net.sf.maltcms.chromaui.charts.FastHeatMapPlot.java

/**
 * Draws the fast scatter plot on a Java 2D graphics device (such as the
 * screen or a printer)./*from   w  w  w.j ava 2s  .c om*/
 *
 * @param g2 the graphics device.
 * @param area the area within which the plot (including axis labels) should
 * be drawn.
 * @param anchor the anchor point (<code>null</code> permitted).
 * @param parentState the state from the parent plot (ignored).
 * @param info collects chart drawing information (<code>null</code>
 * permitted).
 */
@Override
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState,
        PlotRenderingInfo info) {

    // set up info collection...
    if (info != null) {
        info.setPlotArea(area);
    }

    // adjust the drawing area for plot insets (if any)...
    RectangleInsets insets = getInsets();
    insets.trim(area);

    AxisSpace space = new AxisSpace();
    space = this.domainAxis.reserveSpace(g2, this, area, RectangleEdge.BOTTOM, space);
    space = this.rangeAxis.reserveSpace(g2, this, area, RectangleEdge.LEFT, space);
    Rectangle2D dataArea = space.shrink(area, null);

    if (info != null) {
        info.setDataArea(dataArea);
    }

    // draw the plot background and axes...
    drawBackground(g2, dataArea);

    AxisState domainAxisState = this.domainAxis.draw(g2, dataArea.getMaxY(), area, dataArea,
            RectangleEdge.BOTTOM, info);
    AxisState rangeAxisState = this.rangeAxis.draw(g2, dataArea.getMinX(), area, dataArea, RectangleEdge.LEFT,
            info);
    drawDomainGridlines(g2, dataArea, domainAxisState.getTicks());
    drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks());

    Shape originalClip = g2.getClip();
    Composite originalComposite = g2.getComposite();

    g2.clip(dataArea);
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha()));
    render(g2, dataArea, info, null);

    g2.setClip(originalClip);
    g2.setComposite(originalComposite);
    drawOutline(g2, dataArea);

}