List of usage examples for java.awt Graphics2D clip
public abstract void clip(Shape s);
From source file:net.sf.jasperreports.engine.export.JExcelApiMetadataExporter.java
public void exportImage(JRPrintImage element) throws JRException { String currentColumnName = element.getPropertiesMap() .getProperty(JRXlsAbstractMetadataExporterParameter.PROPERTY_COLUMN_NAME); if (currentColumnName != null && currentColumnName.length() > 0) { boolean repeatValue = getPropertiesUtil().getBooleanProperty(element, JRXlsAbstractMetadataExporterParameter.PROPERTY_REPEAT_VALUE, false); setColumnName(currentColumnName); setColumnWidth(columnNamesMap.get(currentColumnName), element.getWidth()); setRowHeight(rowIndex, element.getHeight()); 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())); int availableImageWidth = element.getWidth() - leftPadding - rightPadding; availableImageWidth = availableImageWidth < 0 ? 0 : availableImageWidth; int availableImageHeight = element.getHeight() - topPadding - bottomPadding; availableImageHeight = availableImageHeight < 0 ? 0 : availableImageHeight; Renderable renderer = element.getRenderable(); if (renderer != null && availableImageWidth > 0 && availableImageHeight > 0) { if (renderer.getTypeValue() == RenderableTypeEnum.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 = RenderableUtil.getInstance(jasperReportsContext) .getOnErrorRendererForImageData(renderer, element.getOnErrorTypeValue()); if (renderer != null) { renderer = RenderableUtil.getInstance(jasperReportsContext) .getOnErrorRendererForDimension(renderer, element.getOnErrorTypeValue()); }/* w w w . j a v a 2 s. c om*/ } else { renderer = new JRWrappingSvgRenderer(renderer, new Dimension(element.getWidth(), element.getHeight()), ModeEnum.OPAQUE == element.getModeValue() ? element.getBackcolor() : null); } } else { renderer = null; } if (renderer != null) { int normalWidth = availableImageWidth; int normalHeight = availableImageHeight; Dimension2D dimension = renderer.getDimension(jasperReportsContext); if (dimension != null) { normalWidth = (int) dimension.getWidth(); normalHeight = (int) dimension.getHeight(); } float xalignFactor = 0f; switch (element.getHorizontalAlignmentValue()) { case RIGHT: { xalignFactor = 1f; break; } case CENTER: { xalignFactor = 0.5f; break; } case LEFT: default: { xalignFactor = 0f; break; } } float yalignFactor = 0f; switch (element.getVerticalAlignmentValue()) { case BOTTOM: { yalignFactor = 1f; break; } case MIDDLE: { yalignFactor = 0.5f; break; } case TOP: default: { yalignFactor = 0f; break; } } byte[] imageData = null; switch (element.getScaleImageValue()) { case CLIP: { int dpi = getPropertiesUtil().getIntegerProperty(Renderable.PROPERTY_IMAGE_DPI, 72); double scale = dpi / 72d; BufferedImage bi = new BufferedImage((int) (scale * availableImageWidth), (int) (scale * availableImageHeight), BufferedImage.TYPE_INT_ARGB); Graphics2D grx = bi.createGraphics(); grx.scale(scale, scale); grx.clip(new Rectangle(0, 0, availableImageWidth, availableImageHeight)); renderer.render(jasperReportsContext, grx, new Rectangle((int) (xalignFactor * (availableImageWidth - normalWidth)), (int) (yalignFactor * (availableImageHeight - normalHeight)), normalWidth, normalHeight)); imageData = JRImageLoader.getInstance(jasperReportsContext).loadBytesFromAwtImage(bi, ImageTypeEnum.PNG); break; } case FILL_FRAME: { imageData = renderer.getImageData(jasperReportsContext); break; } case 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; } imageData = renderer.getImageData(jasperReportsContext); } break; } } Pattern mode = this.backgroundMode; Colour background = WHITE; JxlReportConfiguration configuration = getCurrentItemConfiguration(); if (!configuration.isIgnoreCellBackground() && element.getBackcolor() != null) { mode = Pattern.SOLID; background = getWorkbookColour(element.getBackcolor(), true); } if (element.getModeValue() == ModeEnum.OPAQUE) { background = getWorkbookColour(element.getBackcolor(), true); } Colour forecolor = getWorkbookColour(element.getLineBox().getPen().getLineColor()); WritableFont cellFont2 = this.getLoadedFont(getDefaultFont(), forecolor.getValue(), getLocale()); WritableCellFormat cellStyle2 = getLoadedCellStyle(mode, background, cellFont2, new BoxStyle(element), isCellLocked(element)); addBlankElement(cellStyle2, repeatValue, currentColumnName); try { int colIndex = columnNamesMap.get(currentColumnName); WritableImage image = new WritableImage(colIndex, rowIndex, 1, 1, imageData); ImageAnchorTypeEnum imageAnchorType = ImageAnchorTypeEnum.getByName(JRPropertiesUtil .getOwnProperty(element, XlsReportConfiguration.PROPERTY_IMAGE_ANCHOR_TYPE)); if (imageAnchorType == null) { imageAnchorType = configuration.getImageAnchorType(); if (imageAnchorType == null) { imageAnchorType = ImageAnchorTypeEnum.MOVE_NO_SIZE; } } setAnchorType(image, imageAnchorType); sheet.addImage(image); } 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:org.proteosuite.FastScatterPlot.java
/** * Draws the fast scatter plot on a Java 2D graphics device (such as the * screen or a printer).// w w w . j a v a 2s. co m * * @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.jasperreports.engine.export.JExcelApiExporter.java
public void exportImage(JRPrintImage element, JRExporterGridCell gridCell, int col, int row, int emptyCols, int yCutsRow, JRGridLayout layout) throws JRException { addMergeRegion(gridCell, col, row);//from w ww .j a va2 s . c o 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())); int availableImageWidth = element.getWidth() - leftPadding - rightPadding; availableImageWidth = availableImageWidth < 0 ? 0 : availableImageWidth; int availableImageHeight = element.getHeight() - topPadding - bottomPadding; availableImageHeight = availableImageHeight < 0 ? 0 : availableImageHeight; Renderable renderer = element.getRenderable(); if (renderer != null && availableImageWidth > 0 && availableImageHeight > 0) { if (renderer.getTypeValue() == RenderableTypeEnum.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 = RenderableUtil.getInstance(jasperReportsContext).getOnErrorRendererForImageData(renderer, element.getOnErrorTypeValue()); if (renderer != null) { renderer = RenderableUtil.getInstance(jasperReportsContext) .getOnErrorRendererForDimension(renderer, element.getOnErrorTypeValue()); } } else { renderer = new JRWrappingSvgRenderer(renderer, new Dimension(element.getWidth(), element.getHeight()), ModeEnum.OPAQUE == element.getModeValue() ? element.getBackcolor() : null); } } else { renderer = null; } if (renderer != null) { int normalWidth = availableImageWidth; int normalHeight = availableImageHeight; Dimension2D dimension = renderer.getDimension(jasperReportsContext); if (dimension != null) { normalWidth = (int) dimension.getWidth(); normalHeight = (int) dimension.getHeight(); } float xalignFactor = 0f; switch (element.getHorizontalAlignmentValue()) { case RIGHT: { xalignFactor = 1f; break; } case CENTER: { xalignFactor = 0.5f; break; } case LEFT: default: { xalignFactor = 0f; break; } } float yalignFactor = 0f; switch (element.getVerticalAlignmentValue()) { case BOTTOM: { yalignFactor = 1f; break; } case MIDDLE: { yalignFactor = 0.5f; break; } case TOP: default: { yalignFactor = 0f; break; } } byte[] imageData = null; int topOffset = 0; int leftOffset = 0; int bottomOffset = 0; int rightOffset = 0; switch (element.getScaleImageValue()) { case CLIP: { int dpi = getPropertiesUtil().getIntegerProperty(Renderable.PROPERTY_IMAGE_DPI, 72); double scale = dpi / 72d; BufferedImage bi = new BufferedImage((int) (scale * availableImageWidth), (int) (scale * availableImageHeight), BufferedImage.TYPE_INT_ARGB); Graphics2D grx = bi.createGraphics(); grx.scale(scale, scale); grx.clip(new Rectangle(0, 0, availableImageWidth, availableImageHeight)); renderer.render(jasperReportsContext, grx, new Rectangle((int) (xalignFactor * (availableImageWidth - normalWidth)), (int) (yalignFactor * (availableImageHeight - normalHeight)), normalWidth, normalHeight)); topOffset = topPadding; leftOffset = leftPadding; bottomOffset = bottomPadding; rightOffset = rightPadding; imageData = JRImageLoader.getInstance(jasperReportsContext).loadBytesFromAwtImage(bi, ImageTypeEnum.PNG); break; } case FILL_FRAME: { topOffset = topPadding; leftOffset = leftPadding; bottomOffset = bottomPadding; rightOffset = rightPadding; imageData = renderer.getImageData(jasperReportsContext); break; } case 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; } topOffset = topPadding + (int) (yalignFactor * (availableImageHeight - normalHeight)); leftOffset = leftPadding + (int) (xalignFactor * (availableImageWidth - normalWidth)); bottomOffset = bottomPadding + (int) ((1f - yalignFactor) * (availableImageHeight - normalHeight)); rightOffset = rightPadding + (int) ((1f - xalignFactor) * (availableImageWidth - normalWidth)); imageData = renderer.getImageData(jasperReportsContext); } break; } } Pattern mode = this.backgroundMode; Colour background = WHITE; JxlReportConfiguration configuration = getCurrentItemConfiguration(); if (!configuration.isIgnoreCellBackground() && gridCell.getCellBackcolor() != null) { mode = Pattern.SOLID; background = getWorkbookColour(gridCell.getCellBackcolor(), true); } if (element.getModeValue() == ModeEnum.OPAQUE) { background = getWorkbookColour(element.getBackcolor(), true); } Colour forecolor = getWorkbookColour(element.getLineBox().getPen().getLineColor()); WritableFont cellFont2 = this.getLoadedFont(getDefaultFont(), forecolor.getValue(), getLocale()); WritableCellFormat cellStyle2 = getLoadedCellStyle(mode, background, cellFont2, gridCell, isCellLocked(element)); if (!configuration.isIgnoreAnchors() && element.getAnchorName() != null) { int lastCol = Math.max(0, col + gridCell.getColSpan() - 1); int lastRow = Math.max(0, row + gridCell.getRowSpan() - 1); workbook.addNameArea(element.getAnchorName(), sheet, col, row, lastCol, lastRow); } Boolean ignoreHyperlink = HyperlinkUtil .getIgnoreHyperlink(XlsReportConfiguration.PROPERTY_IGNORE_HYPERLINK, element); if (ignoreHyperlink == null) { ignoreHyperlink = configuration.isIgnoreHyperlink(); } if (!ignoreHyperlink) { exportHyperlink(element, "", gridCell, col, row); } try { sheet.addCell(new Blank(col, row, cellStyle2)); double leftPos = getColumnRelativePosition(layout, col, leftOffset); double topPos = getRowRelativePosition(layout, yCutsRow, topOffset); double rightPos = getColumnRelativePosition(layout, col, element.getWidth() - rightOffset); double bottomPos = getRowRelativePosition(layout, yCutsRow, element.getHeight() - bottomOffset); WritableImage image = new WritableImage(col + leftPos, row + topPos, rightPos - leftPos, bottomPos - topPos, imageData); ImageAnchorTypeEnum imageAnchorType = ImageAnchorTypeEnum.getByName(JRPropertiesUtil .getOwnProperty(element, XlsReportConfiguration.PROPERTY_IMAGE_ANCHOR_TYPE)); if (imageAnchorType == null) { imageAnchorType = configuration.getImageAnchorType(); if (imageAnchorType == null) { imageAnchorType = ImageAnchorTypeEnum.MOVE_NO_SIZE; } } setAnchorType(image, imageAnchorType); sheet.addImage(image); } 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:spinworld.gui.RadarPlot.java
/** * Draws the plot on a Java 2D graphics device (such as the screen or a * printer)./*from ww w . ja v a 2s .c o m*/ * * @param g2 the graphics device. * @param area the area within which the plot 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 info about the drawing. */ public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { // adjust for insets... RectangleInsets insets = getInsets(); insets.trim(area); if (info != null) { info.setPlotArea(area); info.setDataArea(area); } drawBackground(g2, area); drawOutline(g2, area); Shape savedClip = g2.getClip(); g2.clip(area); Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); if (!DatasetUtilities.isEmptyOrNull(this.dataset)) { int seriesCount = 0, catCount = 0; if (this.dataExtractOrder == TableOrder.BY_ROW) { seriesCount = this.dataset.getRowCount(); catCount = this.dataset.getColumnCount(); } else { seriesCount = this.dataset.getColumnCount(); catCount = this.dataset.getRowCount(); } // ensure we have origin and maximum value for each axis ensureBoundaryValues(seriesCount, catCount); // Next, setup the plot area // adjust the plot area by the interior spacing value double gapHorizontal = area.getWidth() * getInteriorGap(); double gapVertical = area.getHeight() * getInteriorGap(); double X = area.getX() + gapHorizontal / 2; double Y = area.getY() + gapVertical / 2; double W = area.getWidth() - gapHorizontal; double H = area.getHeight() - gapVertical; double headW = area.getWidth() * this.headPercent; double headH = area.getHeight() * this.headPercent; // make the chart area a square double min = Math.min(W, H) / 2; X = (X + X + W) / 2 - min; Y = (Y + Y + H) / 2 - min; W = 2 * min; H = 2 * min; Point2D centre = new Point2D.Double(X + W / 2, Y + H / 2); Rectangle2D radarArea = new Rectangle2D.Double(X, Y, W, H); // draw the axis and category label for (int cat = 0; cat < catCount; cat++) { double angle = getStartAngle() + (getDirection().getFactor() * cat * 360 / catCount); Point2D endPoint = getWebPoint(radarArea, angle, 1); // 1 = end of axis Line2D line = new Line2D.Double(centre, endPoint); g2.setPaint(this.axisLinePaint); g2.setStroke(this.axisLineStroke); g2.draw(line); if (isAxisTickVisible()) { drawTicks(g2, radarArea, angle, cat); } drawLabel(g2, area, radarArea, 0.0, cat, angle, 360.0 / catCount); } // Now actually plot each of the series polygons.. for (int series = 0; series < seriesCount; series++) { drawRadarPoly(g2, radarArea, centre, info, series, catCount, headH, headW); } } else { drawNoDataMessage(g2, area); } g2.setClip(savedClip); g2.setComposite(originalComposite); drawOutline(g2, area); }
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 a va 2s .com*/ * * @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); }
From source file:org.tsho.dmc2.core.chart.AbstractDmcPlot.java
/** * Draws the fast scatter plot on a Java 2D graphics device (such as the screen or * a printer).//from ww w.j a va 2s . co m * * @param g2 the graphics device. * @param plotArea the area within which the plot (including axis labels) should be drawn. * @param info collects chart drawing information (<code>null</code> permitted). */ public void draw(Graphics2D g2, Rectangle2D plotArea, PlotState parentState, PlotRenderingInfo info) { // if (data == null) // return; // set up info collection... if (info != null) { info.setPlotArea(plotArea); } // adjust the drawing area for plot insets (if any)... Insets insets = getInsets(); if (insets != null) { plotArea.setRect(plotArea.getX() + insets.left, plotArea.getY() + insets.top, plotArea.getWidth() - insets.left - insets.right, plotArea.getHeight() - insets.top - insets.bottom); } AxisSpace space = new AxisSpace(); space = this.domainAxis.reserveSpace(g2, this, plotArea, RectangleEdge.BOTTOM, space); space = this.rangeAxis.reserveSpace(g2, this, plotArea, RectangleEdge.LEFT, space); Rectangle2D dataArea = space.shrink(plotArea, null); if (info != null) { info.setDataArea(dataArea); } // draw the plot background and axes... drawBackground(g2, dataArea); /* if automatic bounds... */ if (!isNoData()) { if (this instanceof DmcRenderablePlot) { DmcPlotRenderer renderer; renderer = ((DmcRenderablePlot) this).getPlotRenderer(); if (renderer != null) { renderer.initialize(); if (renderer.getState() == DmcPlotRenderer.STATE_STOPPED) { return; } } } } AxisState domainAxisState = null, rangeAxisState = null; if (this.domainAxis != null) { double cursor; cursor = dataArea.getMaxY(); domainAxisState = this.domainAxis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.BOTTOM, info); // cursor = info.getCursor(); } if (this.rangeAxis != null) { double cursor; cursor = dataArea.getMinX(); rangeAxisState = this.rangeAxis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.LEFT, info); } if (drawGridlines == true && domainAxisState != null && rangeAxisState != null) { drawGridlines(g2, dataArea, domainAxisState.getTicks(), rangeAxisState.getTicks()); } Shape originalClip = g2.getClip(); g2.clip(dataArea); // Composite originalComposite = g2.getComposite(); // g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, // getForegroundAlpha())); // g2.setStroke(new BasicStroke(12.0F)); if (isNoData()) { drawNoDataMessage(g2, plotArea); } else { drawPlot(g2, dataArea, info); } g2.setClip(originalClip); drawOutline(g2, dataArea); }
From source file:CompositeEffects.java
/** Draw the example */ public void paint(Graphics g1) { Graphics2D g = (Graphics2D) g1; // fill the background g.setPaint(new Color(175, 175, 175)); g.fillRect(0, 0, getWidth(), getHeight()); // Set text attributes g.setColor(Color.black);/*from www .j a v a 2 s. com*/ g.setFont(new Font("SansSerif", Font.BOLD, 12)); // Draw the unmodified image g.translate(10, 10); g.drawImage(cover, 0, 0, this); g.drawString("SRC_OVER", 0, COVERHEIGHT + 15); // Draw the cover again, using AlphaComposite to make the opaque // colors of the image 50% translucent g.translate(COVERWIDTH + 10, 0); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); g.drawImage(cover, 0, 0, this); // Restore the pre-defined default Composite for the screen, so // opaque colors stay opaque. g.setComposite(AlphaComposite.SrcOver); // Label the effect g.drawString("SRC_OVER, 50%", 0, COVERHEIGHT + 15); // Now get an offscreen image to work with. In order to achieve // certain compositing effects, the drawing surface must support // transparency. Onscreen drawing surfaces cannot, so we have to do the // compositing in an offscreen image that is specially created to have // an "alpha channel", then copy the final result to the screen. BufferedImage offscreen = new BufferedImage(COVERWIDTH, COVERHEIGHT, BufferedImage.TYPE_INT_ARGB); // First, fill the image with a color gradient background that varies // left-to-right from opaque to transparent yellow Graphics2D osg = offscreen.createGraphics(); osg.setPaint(new GradientPaint(0, 0, Color.yellow, COVERWIDTH, 0, new Color(255, 255, 0, 0))); osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT); // Now copy the cover image on top of this, but use the DstOver rule // which draws it "underneath" the existing pixels, and allows the // image to show depending on the transparency of those pixels. osg.setComposite(AlphaComposite.DstOver); osg.drawImage(cover, 0, 0, this); // And display this composited image on the screen. Note that the // image is opaque and that none of the screen background shows through g.translate(COVERWIDTH + 10, 0); g.drawImage(offscreen, 0, 0, this); g.drawString("DST_OVER", 0, COVERHEIGHT + 15); // Now start over and do a new effect with the off-screen image. // First, fill the offscreen image with a new color gradient. We // don't care about the colors themselves; we just want the // translucency of the background to vary. We use opaque black to // transparent black. Note that since we've already used this offscreen // image, we set the composite to Src, we can fill the image and // ignore anything that is already there. osg.setComposite(AlphaComposite.Src); osg.setPaint(new GradientPaint(0, 0, Color.black, COVERWIDTH, COVERHEIGHT, new Color(0, 0, 0, 0))); osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT); // Now set the compositing type to SrcIn, so colors come from the // source, but translucency comes from the destination osg.setComposite(AlphaComposite.SrcIn); // Draw our loaded image into the off-screen image, compositing it. osg.drawImage(cover, 0, 0, this); // And then copy our off-screen image to the screen. Note that the // image is translucent and some of the image shows through. g.translate(COVERWIDTH + 10, 0); g.drawImage(offscreen, 0, 0, this); g.drawString("SRC_IN", 0, COVERHEIGHT + 15); // If we do the same thing but use SrcOut, then the resulting image // will have the inverted translucency values of the destination osg.setComposite(AlphaComposite.Src); osg.setPaint(new GradientPaint(0, 0, Color.black, COVERWIDTH, COVERHEIGHT, new Color(0, 0, 0, 0))); osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT); osg.setComposite(AlphaComposite.SrcOut); osg.drawImage(cover, 0, 0, this); g.translate(COVERWIDTH + 10, 0); g.drawImage(offscreen, 0, 0, this); g.drawString("SRC_OUT", 0, COVERHEIGHT + 15); // Here's a cool effect; it has nothing to do with compositing, but // uses an arbitrary shape to clip the image. It uses Area to combine // shapes into more complicated ones. g.translate(COVERWIDTH + 10, 0); Shape savedClip = g.getClip(); // Save current clipping region // Create a shape to use as the new clipping region. // Begin with an ellipse Area clip = new Area(new Ellipse2D.Float(0, 0, COVERWIDTH, COVERHEIGHT)); // Intersect with a rectangle, truncating the ellipse. clip.intersect(new Area(new Rectangle(5, 5, COVERWIDTH - 10, COVERHEIGHT - 10))); // Then subtract an ellipse from the bottom of the truncated ellipse. clip.subtract(new Area(new Ellipse2D.Float(COVERWIDTH / 2 - 40, COVERHEIGHT - 20, 80, 40))); // Use the resulting shape as the new clipping region g.clip(clip); // Then draw the image through this clipping region g.drawImage(cover, 0, 0, this); // Restore the old clipping region so we can label the effect g.setClip(savedClip); g.drawString("Clipping", 0, COVERHEIGHT + 15); }
From source file:ucar.unidata.idv.control.chart.MyXYPlot.java
/** * Draws the plot within the specified area on a graphics device. * * @param g2 the graphics device./* w w w . j av a 2s . c o m*/ * @param area the plot area (in Java2D space). * @param anchor an anchor point in Java2D space (<code>null</code> * permitted). * @param parentState the state from the parent plot, if there is one * (<code>null</code> permitted). * @param info collects chart drawing information (<code>null</code> * permitted). */ public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { // if the plot area is too small, just return... boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW); boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW); if (b1 || b2) { return; } // record the plot area... if (info != null) { info.setPlotArea(area); } // adjust the drawing area for the plot insets (if any)... RectangleInsets insets = getInsets(); insets.trim(area); AxisSpace space = calculateAxisSpace(g2, area); Rectangle2D dataArea = space.shrink(area, null); this.axisOffset.trim(dataArea); if (info != null) { info.setDataArea(dataArea); } // draw the plot background and axes... drawBackground(g2, dataArea); Map axisStateMap = drawAxes(g2, area, dataArea, info); if ((anchor != null) && !dataArea.contains(anchor)) { anchor = null; } CrosshairState crosshairState = new CrosshairState(); crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY); crosshairState.setAnchor(anchor); crosshairState.setCrosshairX(getDomainCrosshairValue()); crosshairState.setCrosshairY(getRangeCrosshairValue()); Shape originalClip = g2.getClip(); Composite originalComposite = g2.getComposite(); g2.clip(dataArea); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); AxisState domainAxisState = (AxisState) axisStateMap.get(getDomainAxis()); if (domainAxisState == null) { if (parentState != null) { domainAxisState = (AxisState) parentState.getSharedAxisStates().get(getDomainAxis()); } } if (domainAxisState != null) { drawDomainTickBands(g2, dataArea, domainAxisState.getTicks()); drawDomainGridlines(g2, dataArea, domainAxisState.getTicks()); } AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis()); if (rangeAxisState == null) { if (parentState != null) { rangeAxisState = (AxisState) parentState.getSharedAxisStates().get(getRangeAxis()); } } if (rangeAxisState != null) { drawRangeTickBands(g2, dataArea, rangeAxisState.getTicks()); drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks()); drawZeroRangeBaseline(g2, dataArea); } // draw the markers that are associated with a specific renderer... for (int i = 0; i < this.renderers.size(); i++) { drawDomainMarkers(g2, dataArea, i, Layer.BACKGROUND); } for (int i = 0; i < this.renderers.size(); i++) { drawRangeMarkers(g2, dataArea, i, Layer.BACKGROUND); } // now draw annotations and render data items... boolean foundData = false; DatasetRenderingOrder order = getDatasetRenderingOrder(); if (order == DatasetRenderingOrder.FORWARD) { // draw background annotations int rendererCount = this.renderers.size(); for (int i = 0; i < rendererCount; i++) { XYItemRenderer r = getRenderer(i); if (r != null) { ValueAxis domainAxis = getDomainAxisForDataset(i); ValueAxis rangeAxis = getRangeAxisForDataset(i); r.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, Layer.BACKGROUND, info); } } // render data items... for (int i = 0; i < getDatasetCount(); i++) { foundData = render(g2, dataArea, i, info, crosshairState) || foundData; } // draw foreground annotations for (int i = 0; i < rendererCount; i++) { XYItemRenderer r = getRenderer(i); if (r != null) { ValueAxis domainAxis = getDomainAxisForDataset(i); ValueAxis rangeAxis = getRangeAxisForDataset(i); r.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, Layer.FOREGROUND, info); } } } else if (order == DatasetRenderingOrder.REVERSE) { // draw background annotations int rendererCount = this.renderers.size(); for (int i = rendererCount - 1; i >= 0; i--) { XYItemRenderer r = getRenderer(i); if (r != null) { ValueAxis domainAxis = getDomainAxisForDataset(i); ValueAxis rangeAxis = getRangeAxisForDataset(i); r.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, Layer.BACKGROUND, info); } } ucar.unidata.util.Trace.call1("renderData"); for (int i = getDatasetCount() - 1; i >= 0; i--) { foundData = render(g2, dataArea, i, info, crosshairState) || foundData; } ucar.unidata.util.Trace.call2("renderData"); // draw foreground annotations for (int i = rendererCount - 1; i >= 0; i--) { XYItemRenderer r = getRenderer(i); if (r != null) { ValueAxis domainAxis = getDomainAxisForDataset(i); ValueAxis rangeAxis = getRangeAxisForDataset(i); r.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, Layer.FOREGROUND, info); } } } PlotOrientation orient = getOrientation(); // draw domain crosshair if required... if (!this.domainCrosshairLockedOnData && (anchor != null)) { double xx = getDomainAxis().java2DToValue(anchor.getX(), dataArea, getDomainAxisEdge()); crosshairState.setCrosshairX(xx); } setDomainCrosshairValue(crosshairState.getCrosshairX(), false); if (isDomainCrosshairVisible()) { double x = getDomainCrosshairValue(); Paint paint = getDomainCrosshairPaint(); Stroke stroke = getDomainCrosshairStroke(); if (orient == PlotOrientation.HORIZONTAL) { drawHorizontalLine(g2, dataArea, x, stroke, paint); } else if (orient == PlotOrientation.VERTICAL) { drawVerticalLine(g2, dataArea, x, stroke, paint); } } // draw range crosshair if required... if (!this.rangeCrosshairLockedOnData && (anchor != null)) { double yy = getRangeAxis().java2DToValue(anchor.getY(), dataArea, getRangeAxisEdge()); crosshairState.setCrosshairX(yy); } setRangeCrosshairValue(crosshairState.getCrosshairY(), false); if (isRangeCrosshairVisible() && getRangeAxis().getRange().contains(getRangeCrosshairValue())) { double y = getRangeCrosshairValue(); Paint paint = getRangeCrosshairPaint(); Stroke stroke = getRangeCrosshairStroke(); if (orient == PlotOrientation.HORIZONTAL) { drawVerticalLine(g2, dataArea, y, stroke, paint); } else if (orient == PlotOrientation.VERTICAL) { drawHorizontalLine(g2, dataArea, y, stroke, paint); } } if (!foundData) { drawNoDataMessage(g2, dataArea); } for (int i = 0; i < this.renderers.size(); i++) { drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND); } for (int i = 0; i < this.renderers.size(); i++) { drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND); } drawAnnotations(g2, dataArea, info); g2.setClip(originalClip); g2.setComposite(originalComposite); drawOutline(g2, dataArea); }
From source file:org.apache.fop.afp.AFPGraphics2D.java
/** * Draws an AWT image into a BufferedImage using an AWT Graphics2D implementation * * @param img the AWT image/*from ww w . j a va2 s . co m*/ * @param bufferedImage the AWT buffered image * @param width the image width * @param height the image height * @param observer the image observer * @return true if the image was drawn */ private boolean drawBufferedImage(Image img, BufferedImage bufferedImage, int width, int height, ImageObserver observer) { java.awt.Graphics2D g2d = bufferedImage.createGraphics(); try { g2d.setComposite(AlphaComposite.SrcOver); Color color = new Color(1, 1, 1, 0); g2d.setBackground(color); g2d.setPaint(color); g2d.fillRect(0, 0, width, height); int imageWidth = bufferedImage.getWidth(); int imageHeight = bufferedImage.getHeight(); Rectangle clipRect = new Rectangle(0, 0, imageWidth, imageHeight); g2d.clip(clipRect); g2d.setComposite(gc.getComposite()); return g2d.drawImage(img, 0, 0, imageWidth, imageHeight, observer); } finally { g2d.dispose(); //drawn so dispose immediately to free system resource } }
From source file:org.apache.fop.render.pcl.PCLRenderer.java
/** * Draws borders. Borders are drawn in-memory and painted as a bitmap. * @param borderRect the border rectangle * @param bpsBefore the border specification on the before side * @param bpsAfter the border specification on the after side * @param bpsStart the border specification on the start side * @param bpsEnd the border specification on the end side *///from ww w. j av a 2 s .c om protected void drawQualityBorders(Rectangle2D.Float borderRect, final BorderProps bpsBefore, final BorderProps bpsAfter, final BorderProps bpsStart, final BorderProps bpsEnd) { Graphics2DAdapter g2a = getGraphics2DAdapter(); final Rectangle.Float effBorderRect = new Rectangle2D.Float(0, 0, borderRect.width, borderRect.height); final Rectangle paintRect = new Rectangle(Math.round(borderRect.x * 1000f), Math.round(borderRect.y * 1000f), (int) Math.floor(borderRect.width * 1000f) + 1, (int) Math.floor(borderRect.height * 1000f) + 1); //Add one pixel wide safety margin around the paint area int pixelWidth = (int) Math.round(UnitConv.in2mpt(1) / userAgent.getTargetResolution()); final int xoffset = Math.round(-effBorderRect.x * 1000f) + pixelWidth; final int yoffset = pixelWidth; paintRect.x += xoffset; paintRect.y += yoffset; paintRect.width += 2 * pixelWidth; paintRect.height += 2 * pixelWidth; RendererContext rc = createRendererContext(paintRect.x, paintRect.y, paintRect.width, paintRect.height, null); Map atts = new java.util.HashMap(); atts.put(ImageHandlerUtil.CONVERSION_MODE, ImageHandlerUtil.CONVERSION_MODE_BITMAP); atts.put(SRC_TRANSPARENCY, "true"); rc.setProperty(RendererContextConstants.FOREIGN_ATTRIBUTES, atts); Graphics2DImagePainter painter = new Graphics2DImagePainter() { public void paint(Graphics2D g2d, Rectangle2D area) { g2d.translate(xoffset, yoffset); g2d.scale(1000, 1000); float startx = effBorderRect.x; float starty = effBorderRect.y; float width = effBorderRect.width; float height = effBorderRect.height; boolean[] b = new boolean[] { (bpsBefore != null), (bpsEnd != null), (bpsAfter != null), (bpsStart != null) }; if (!b[0] && !b[1] && !b[2] && !b[3]) { return; } float[] bw = new float[] { (b[0] ? bpsBefore.width / 1000f : 0.0f), (b[1] ? bpsEnd.width / 1000f : 0.0f), (b[2] ? bpsAfter.width / 1000f : 0.0f), (b[3] ? bpsStart.width / 1000f : 0.0f) }; float[] clipw = new float[] { BorderProps.getClippedWidth(bpsBefore) / 1000f, BorderProps.getClippedWidth(bpsEnd) / 1000f, BorderProps.getClippedWidth(bpsAfter) / 1000f, BorderProps.getClippedWidth(bpsStart) / 1000f }; starty += clipw[0]; height -= clipw[0]; height -= clipw[2]; startx += clipw[3]; width -= clipw[3]; width -= clipw[1]; boolean[] slant = new boolean[] { (b[3] && b[0]), (b[0] && b[1]), (b[1] && b[2]), (b[2] && b[3]) }; if (bpsBefore != null) { //endTextObject(); float sx1 = startx; float sx2 = (slant[0] ? sx1 + bw[3] - clipw[3] : sx1); float ex1 = startx + width; float ex2 = (slant[1] ? ex1 - bw[1] + clipw[1] : ex1); float outery = starty - clipw[0]; float clipy = outery + clipw[0]; float innery = outery + bw[0]; //saveGraphicsState(); Graphics2D g = (Graphics2D) g2d.create(); moveTo(sx1, clipy); float sx1a = sx1; float ex1a = ex1; if (bpsBefore.mode == BorderProps.COLLAPSE_OUTER) { if (bpsStart != null && bpsStart.mode == BorderProps.COLLAPSE_OUTER) { sx1a -= clipw[3]; } if (bpsEnd != null && bpsEnd.mode == BorderProps.COLLAPSE_OUTER) { ex1a += clipw[1]; } lineTo(sx1a, outery); lineTo(ex1a, outery); } lineTo(ex1, clipy); lineTo(ex2, innery); lineTo(sx2, innery); closePath(); //clip(); g.clip(currentPath); currentPath = null; Rectangle2D.Float lineRect = new Rectangle2D.Float(sx1a, outery, ex1a - sx1a, innery - outery); Java2DRenderer.drawBorderLine(lineRect, true, true, bpsBefore.style, bpsBefore.color, g); //restoreGraphicsState(); } if (bpsEnd != null) { //endTextObject(); float sy1 = starty; float sy2 = (slant[1] ? sy1 + bw[0] - clipw[0] : sy1); float ey1 = starty + height; float ey2 = (slant[2] ? ey1 - bw[2] + clipw[2] : ey1); float outerx = startx + width + clipw[1]; float clipx = outerx - clipw[1]; float innerx = outerx - bw[1]; //saveGraphicsState(); Graphics2D g = (Graphics2D) g2d.create(); moveTo(clipx, sy1); float sy1a = sy1; float ey1a = ey1; if (bpsEnd.mode == BorderProps.COLLAPSE_OUTER) { if (bpsBefore != null && bpsBefore.mode == BorderProps.COLLAPSE_OUTER) { sy1a -= clipw[0]; } if (bpsAfter != null && bpsAfter.mode == BorderProps.COLLAPSE_OUTER) { ey1a += clipw[2]; } lineTo(outerx, sy1a); lineTo(outerx, ey1a); } lineTo(clipx, ey1); lineTo(innerx, ey2); lineTo(innerx, sy2); closePath(); //clip(); g.setClip(currentPath); currentPath = null; Rectangle2D.Float lineRect = new Rectangle2D.Float(innerx, sy1a, outerx - innerx, ey1a - sy1a); Java2DRenderer.drawBorderLine(lineRect, false, false, bpsEnd.style, bpsEnd.color, g); //restoreGraphicsState(); } if (bpsAfter != null) { //endTextObject(); float sx1 = startx; float sx2 = (slant[3] ? sx1 + bw[3] - clipw[3] : sx1); float ex1 = startx + width; float ex2 = (slant[2] ? ex1 - bw[1] + clipw[1] : ex1); float outery = starty + height + clipw[2]; float clipy = outery - clipw[2]; float innery = outery - bw[2]; //saveGraphicsState(); Graphics2D g = (Graphics2D) g2d.create(); moveTo(ex1, clipy); float sx1a = sx1; float ex1a = ex1; if (bpsAfter.mode == BorderProps.COLLAPSE_OUTER) { if (bpsStart != null && bpsStart.mode == BorderProps.COLLAPSE_OUTER) { sx1a -= clipw[3]; } if (bpsEnd != null && bpsEnd.mode == BorderProps.COLLAPSE_OUTER) { ex1a += clipw[1]; } lineTo(ex1a, outery); lineTo(sx1a, outery); } lineTo(sx1, clipy); lineTo(sx2, innery); lineTo(ex2, innery); closePath(); //clip(); g.setClip(currentPath); currentPath = null; Rectangle2D.Float lineRect = new Rectangle2D.Float(sx1a, innery, ex1a - sx1a, outery - innery); Java2DRenderer.drawBorderLine(lineRect, true, false, bpsAfter.style, bpsAfter.color, g); //restoreGraphicsState(); } if (bpsStart != null) { //endTextObject(); float sy1 = starty; float sy2 = (slant[0] ? sy1 + bw[0] - clipw[0] : sy1); float ey1 = sy1 + height; float ey2 = (slant[3] ? ey1 - bw[2] + clipw[2] : ey1); float outerx = startx - clipw[3]; float clipx = outerx + clipw[3]; float innerx = outerx + bw[3]; //saveGraphicsState(); Graphics2D g = (Graphics2D) g2d.create(); moveTo(clipx, ey1); float sy1a = sy1; float ey1a = ey1; if (bpsStart.mode == BorderProps.COLLAPSE_OUTER) { if (bpsBefore != null && bpsBefore.mode == BorderProps.COLLAPSE_OUTER) { sy1a -= clipw[0]; } if (bpsAfter != null && bpsAfter.mode == BorderProps.COLLAPSE_OUTER) { ey1a += clipw[2]; } lineTo(outerx, ey1a); lineTo(outerx, sy1a); } lineTo(clipx, sy1); lineTo(innerx, sy2); lineTo(innerx, ey2); closePath(); //clip(); g.setClip(currentPath); currentPath = null; Rectangle2D.Float lineRect = new Rectangle2D.Float(outerx, sy1a, innerx - outerx, ey1a - sy1a); Java2DRenderer.drawBorderLine(lineRect, false, false, bpsStart.style, bpsStart.color, g); //restoreGraphicsState(); } } public Dimension getImageSize() { return paintRect.getSize(); } }; try { g2a.paintImage(painter, rc, paintRect.x - xoffset, paintRect.y, paintRect.width, paintRect.height); } catch (IOException ioe) { handleIOTrouble(ioe); } }