Example usage for java.awt Graphics2D setComposite

List of usage examples for java.awt Graphics2D setComposite

Introduction

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

Prototype

public abstract void setComposite(Composite comp);

Source Link

Document

Sets the Composite for the Graphics2D context.

Usage

From source file:org.kalypsodeegree_impl.graphics.displayelements.RasterDisplayElement_Impl.java

private void paintGrid(final Graphics2D g, final IGeoGrid grid, final GeoTransform projection,
        final String mapSRS, final IProgressMonitor monitor)
        throws GeoGridException, CoreException, FilterEvaluationException {
    /* Progress monitor. */
    final SubMonitor progress = SubMonitor.convert(monitor, "Painting grid", 100);

    /* Get the envelope of the surface of the grid (it is transformed). */
    final GM_Polygon gridSurface = grid.getSurface(mapSRS);

    final Composite oldAlphaComposite = g.getComposite();
    try {//ww w  .jav  a2 s  . c  om
        final JTSTransformer map2GridTransformer = new JTSTransformer(mapSRS, grid.getSourceCRS());

        final float opacity = getOpacity();
        if (!Double.isNaN(opacity))
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));

        paintRaster(g, grid, projection, gridSurface, mapSRS, map2GridTransformer,
                progress.newChild(95, SubMonitor.SUPPRESS_NONE));
    } catch (final FactoryException | TransformException e) {
        final IStatus status = new Status(IStatus.ERROR, KalypsoDeegreePlugin.getID(),
                "Failed to initialize geo transformer", e); //$NON-NLS-1$
        throw new CoreException(status);
    } finally {
        g.setComposite(oldAlphaComposite);
    }

    // TODO Tricky: apply opacityFactor to imageOutline as well?
    final RasterSymbolizer symbolizer = (RasterSymbolizer) getSymbolizer();
    final Symbolizer imageOutline = symbolizer.getImageOutline();
    paintImageOutline(g, gridSurface, projection, imageOutline, progress.newChild(5, SubMonitor.SUPPRESS_NONE));
}

From source file:com.codename1.android.AndroidLayoutImporter.java

Border createImageBorder(String imageName) {
    Image im = outputResources.getImage(imageName);
    if (im == null) {
        return null;
    }/*from ww w  . jav a2 s.c om*/
    EncodedImage eim = null;
    if (im instanceof EncodedImage) {
        eim = (EncodedImage) im;
    } else {
        eim = EncodedImage.createFromImage(im, imageName.endsWith(".jpg"));
    }

    BufferedImage center = new BufferedImage(1, im.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = (Graphics2D) center.createGraphics();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
    g2.fillRect(0, 0, im.getWidth(), im.getHeight());
    g2.dispose();

    EncodedImage placeholder = EncodedImage.create(toPng(center));

    outputResources.setImage("TransparentPlaceholer" + center.getWidth() + "x" + center.getHeight() + ".png",
            placeholder);

    return Border.createHorizonalImageBorder(eim, placeholder, placeholder);
}

From source file:org.polymap.service.geoserver.spring.PipelineMapProducer.java

public void writeTo(final OutputStream out) throws ServiceException, IOException {
    Timer timer = new Timer();

    // single layer? -> request ENCODED_IMAGE
    if (mapContext.getLayerCount() == 1) {
        MapLayer mapLayer = mapContext.getLayers()[0];
        ILayer layer = loader.findLayer(mapLayer);
        try {//  w  w w. ja  v  a 2  s  .c o m
            Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.ENCODED_IMAGE);

            ProcessorRequest request = prepareProcessorRequest();
            pipeline.process(request, new ResponseHandler() {
                public void handle(ProcessorResponse pipeResponse) throws Exception {

                    HttpServletResponse response = GeoServerWms.response.get();
                    if (pipeResponse == EncodedImageResponse.NOT_MODIFIED) {
                        log.info("Response: 304!");
                        response.setStatus(304);
                    } else {
                        long lastModified = ((EncodedImageResponse) pipeResponse).getLastModified();
                        // allow caches and browser clients to cache for 1h
                        //response.setHeader( "Cache-Control", "public,max-age=3600" );
                        if (lastModified > 0) {
                            response.setHeader("Cache-Control", "no-cache,must-revalidate");
                            response.setDateHeader("Last-Modified", lastModified);
                        } else {
                            response.setHeader("Cache-Control", "no-cache,must-revalidate");
                            response.setDateHeader("Expires", 0);
                        }

                        byte[] chunk = ((EncodedImageResponse) pipeResponse).getChunk();
                        int len = ((EncodedImageResponse) pipeResponse).getChunkSize();
                        out.write(chunk, 0, len);
                    }
                }
            });
            log.debug("    flushing response stream. (" + timer.elapsedTime() + "ms)");
            out.flush();
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    // multiple layers -> render into one image
    else {
        List<Job> jobs = new ArrayList();
        final Map<MapLayer, Image> images = new HashMap();

        // run jobs for all layers
        for (final MapLayer mapLayer : mapContext.getLayers()) {
            final ILayer layer = loader.findLayer(mapLayer);
            // job
            UIJob job = new UIJob(getClass().getSimpleName() + ": " + layer.getLabel()) {
                protected void runWithException(IProgressMonitor monitor) throws Exception {
                    try {
                        // XXX this excludes Cache304 (which support EncodedImageResponse only)
                        Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.IMAGE);

                        GetMapRequest targetRequest = prepareProcessorRequest();
                        pipeline.process(targetRequest, new ResponseHandler() {
                            public void handle(ProcessorResponse pipeResponse) throws Exception {
                                Image layerImage = ((ImageResponse) pipeResponse).getImage();
                                images.put(mapLayer, layerImage);
                            }
                        });
                    } catch (Exception e) {
                        // XXX put a special image in the map
                        log.warn("", e);
                        images.put(mapLayer, null);
                        throw e;
                    }
                }
            };
            job.schedule();
            jobs.add(job);
        }

        // join jobs
        for (Job job : jobs) {
            try {
                job.join();
            } catch (InterruptedException e) {
                // XXX put a special image in the map
                log.warn("", e);
            }
        }

        // put images together (MapContext order)
        Graphics2D g = null;
        try {
            // result image
            BufferedImage result = ImageUtils.createImage(mapContext.getMapWidth(), mapContext.getMapHeight(),
                    null, true);
            g = result.createGraphics();

            // rendering hints
            RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
            hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
            hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
            g.setRenderingHints(hints);

            for (MapLayer mapLayer : mapContext.getLayers()) {
                Image layerImage = images.get(mapLayer);

                // load image data
                //                  new javax.swing.ImageIcon( image ).getImage();

                ILayer layer = loader.findLayer(mapLayer);
                int rule = AlphaComposite.SRC_OVER;
                float alpha = ((float) layer.getOpacity()) / 100;

                g.setComposite(AlphaComposite.getInstance(rule, alpha));
                g.drawImage(layerImage, 0, 0, null);
            }
            encodeImage(result, out);
        } finally {
            if (g != null) {
                g.dispose();
            }
        }
    }
}

From source file:com.openkm.module.direct.DirectWorkflowModule.java

@Override
public byte[] getProcessDefinitionImage(String token, long processDefinitionId, String node)
        throws RepositoryException, DatabaseException, WorkflowException {
    log.debug("getProcessDefinitionImage({}, {}, {})", new Object[] { token, processDefinitionId, node });
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    byte[] image = null;
    Session session = null;//from w w w.  j  av a2 s. c  om

    try {
        if (token == null) {
            session = JCRUtils.getSession();
        } else {
            session = JcrSessionManager.getInstance().get(token);
        }

        GraphSession graphSession = jbpmContext.getGraphSession();
        org.jbpm.graph.def.ProcessDefinition pd = graphSession.getProcessDefinition(processDefinitionId);
        FileDefinition fileDef = pd.getFileDefinition();

        WorkflowUtils.DiagramInfo dInfo = WorkflowUtils.getDiagramInfo(fileDef.getInputStream("gpd.xml"));
        WorkflowUtils.DiagramNodeInfo dNodeInfo = dInfo.getNodeMap().get(node);
        BufferedImage img = ImageIO.read(fileDef.getInputStream("processimage.jpg"));

        // Obtain all nodes Y
        List<Integer> ordenadas = new ArrayList<Integer>();

        for (WorkflowUtils.DiagramNodeInfo nodeInfo : dInfo.getNodeMap().values()) {
            ordenadas.add(nodeInfo.getY());
        }

        // Calculate minimal Y
        Collections.sort(ordenadas);
        int fix = ordenadas.get(0);

        if (dNodeInfo != null) {
            // Select node
            log.debug("DiagramNodeInfo: {}", dNodeInfo);
            Graphics g = img.getGraphics();
            Graphics2D g2d = (Graphics2D) g;
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.25F));
            g2d.setColor(Color.blue);
            g2d.fillRect(dNodeInfo.getX(), dNodeInfo.getY() - fix, dNodeInfo.getWidth(), dNodeInfo.getHeight());
            g.dispose();
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, "jpg", baos);
        image = baos.toByteArray();
        baos.flush();
        baos.close();

        // Activity log
        UserActivity.log(session.getUserID(), "GET_PROCESS_DEFINITION_IMAGE", "" + processDefinitionId, null);
    } catch (javax.jcr.RepositoryException e) {
        throw new RepositoryException(e.getMessage(), e);
    } catch (JbpmException e) {
        throw new WorkflowException(e.getMessage(), e);
    } catch (IOException e) {
        throw new WorkflowException(e.getMessage(), e);
    } finally {
        if (token == null)
            JCRUtils.logout(session);
        jbpmContext.close();
    }

    log.debug("getProcessDefinitionImage: {}", image);
    return image;
}

From source file:com.joey.software.regionSelectionToolkit.controlers.ImageProfileTool.java

@Override
public void draw(Graphics2D g) {
    if (isBlockUpdate()) {
        return;//w ww .jav  a 2s. c o m
    }
    updateSelectionData();

    float tra = (transparance.getValue() / (float) (transparance.getMaximum()));

    float lineSize = 1f / (float) panel.getScale();
    float crossSize = (float) (pointSize / panel.getScale());

    RenderingHints oldHinds = g.getRenderingHints();
    Composite oldcomp = g.getComposite();
    Stroke oldStroke = g.getStroke();
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, tra));
    g.setStroke(new BasicStroke(lineSize));
    GraphicsToolkit.setRenderingQuality(g, GraphicsToolkit.HIGH_QUALITY);
    Line2D.Double line = new Line2D.Double();

    double x1 = 0;
    double x2 = 0;
    double y1 = 0;
    double y2 = 0;
    for (int i = 0; i < selectionData.length - 1; i++) {
        if (axis == AXIS_X) {
            y1 = view.getImage().getHeight() / (double) (selectionData.length - 1) * i;
            x1 = view.getImage().getWidth() * (1 - getSelectionValue(i));

            y2 = view.getImage().getHeight() / (double) (selectionData.length - 1) * (i + 1);
            x2 = view.getImage().getWidth() * (1 - getSelectionValue(i + 1));
        } else if (axis == AXIS_Y) {
            x1 = view.getImage().getWidth() / (double) (selectionData.length - 1) * i;
            y1 = view.getImage().getHeight() * (1 - getSelectionValue(i));

            x2 = view.getImage().getWidth() / (double) (selectionData.length - 1) * (i + 1);
            y2 = view.getImage().getHeight() * (1 - getSelectionValue(i + 1));
        }

        if (getUseData(i)) {
            g.setColor(getPointColorSelected());
        } else {
            g.setColor(getPointColorNotSelected());
        }
        line.x1 = x1;
        line.x2 = x2;
        line.y1 = y1;
        line.y2 = y2;

        g.draw(line);

        if (showOffset.isSelected()) {
            if (getUseData(i)) {
                g.setColor(getOffsetColor());
                double offset = (Double) this.offset.getValue();

                if (axis == AXIS_X) {
                    line.x1 += offset;
                    line.x2 += offset;

                } else if (axis == AXIS_Y) {
                    line.y1 += offset;
                    line.y2 += offset;
                }
                g.draw(line);
            }
        }
    }

    // Draw each point
    if (drawCrosses) {
        double x = 0;
        double y = 0;
        for (int i = 0; i < value.length; i++) {

            if (axis == AXIS_X) {
                y = view.getImage().getHeight() / (double) (value.length - 1) * i;
                x = view.getImage().getWidth() * (1 - value[i]);
            } else if (axis == AXIS_Y) {
                x = view.getImage().getWidth() / (double) (value.length - 1) * i;
                y = view.getImage().getHeight() * (1 - value[i]);
            }
            DrawTools.drawCross(g, new Point2D.Double(x, y), crossSize, 0, getCrossColor(), lineSize);

        }
    }
    g.setComposite(oldcomp);
    g.setStroke(oldStroke);
    g.setRenderingHints(oldHinds);
}

From source file:forge.view.arcane.util.OutlinedLabel.java

/** {@inheritDoc} */
@Override/*from   w ww  .  j  a v  a  2 s.c om*/
public final void paint(final Graphics g) {
    if (getText().length() == 0) {
        return;
    }

    Dimension size = getSize();
    //
    //        if( size.width < 50 ) {
    //            g.setColor(Color.cyan);
    //            g.drawRect(0, 0, size.width-1, size.height-1);
    //        }

    Graphics2D g2d = (Graphics2D) g;

    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    int textX = outlineSize, textY = 0;
    int wrapWidth = Math.max(0, wrap ? size.width - outlineSize * 2 : Integer.MAX_VALUE);

    final String text = getText();
    AttributedString attributedString = new AttributedString(text);
    if (!StringUtils.isEmpty(text)) {
        attributedString.addAttribute(TextAttribute.FONT, getFont());
    }
    AttributedCharacterIterator charIterator = attributedString.getIterator();
    FontRenderContext fontContext = g2d.getFontRenderContext();

    LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator,
            BreakIterator.getWordInstance(Locale.ENGLISH), fontContext);
    int lineCount = 0;
    while (measurer.getPosition() < charIterator.getEndIndex()) {
        measurer.nextLayout(wrapWidth);
        lineCount++;
        if (lineCount > 2) {
            break;
        }
    }
    charIterator.first();
    // Use char wrap if word wrap would cause more than two lines of text.
    if (lineCount > 2) {
        measurer = new LineBreakMeasurer(charIterator, BreakIterator.getCharacterInstance(Locale.ENGLISH),
                fontContext);
    } else {
        measurer.setPosition(0);
    }
    while (measurer.getPosition() < charIterator.getEndIndex()) {
        TextLayout textLayout = measurer.nextLayout(wrapWidth);
        float ascent = textLayout.getAscent();
        textY += ascent; // Move down to baseline.

        g2d.setColor(outlineColor);
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));

        textLayout.draw(g2d, textX + outlineSize, textY - outlineSize);
        textLayout.draw(g2d, textX + outlineSize, textY + outlineSize);
        textLayout.draw(g2d, textX - outlineSize, textY - outlineSize);
        textLayout.draw(g2d, textX - outlineSize, textY + outlineSize);

        g2d.setColor(getForeground());
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
        textLayout.draw(g2d, textX, textY);

        // Move down to top of next line.
        textY += textLayout.getDescent() + textLayout.getLeading();
    }
}

From source file:com.lfx.web.WebChartXYPlot.java

/**
  * Draws the gridlines for the plot, if they are visible.
  *//from   www . j a  v a 2 s  . c  om
  * @param g2  the graphics device.
  * @param dataArea  the data area.
  * @param ticks  the ticks.
  *
  * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List)
  */

protected void drawRangeGridlines(Graphics2D g2, Rectangle2D dataArea, List ticks) {
    Composite oldcomp = g2.getComposite();
    Paint bandPaint = getBackgroundPaint();
    if (bandPaint != null && bandPaint instanceof java.awt.Color) {
        // g2.setComposite(AlphaComposite.SrcO);
        java.awt.Color bandcolor = (java.awt.Color) (bandPaint);
        boolean fillBand = false;
        ValueAxis axis = getRangeAxis();
        double previous = axis.getLowerBound();
        Iterator iterator = ticks.iterator();
        while (iterator.hasNext()) {
            ValueTick tick = (ValueTick) iterator.next();
            if (!tick.getTickType().equals(TickType.MAJOR))
                continue;
            double current = tick.getValue();
            double y1 = axis.valueToJava2D(previous, dataArea, getRangeAxisEdge());
            double y2 = axis.valueToJava2D(current, dataArea, getRangeAxisEdge());
            Rectangle2D band = new Rectangle2D.Double(dataArea.getMinX(), y2, dataArea.getWidth(), y1 - y2);
            if (fillBand)
                g2.setPaint(bandcolor);
            else
                g2.setPaint(bandcolor.darker());
            g2.fill(band);
            previous = current;
            fillBand = !fillBand;
        }
        double end = axis.getUpperBound();
        double y1 = axis.valueToJava2D(previous, dataArea, getRangeAxisEdge());
        double y2 = axis.valueToJava2D(end, dataArea, getRangeAxisEdge());
        Rectangle2D band = new Rectangle2D.Double(dataArea.getMinX(), y2, dataArea.getWidth(), y1 - y2);
        if (fillBand)
            g2.setPaint(bandcolor);
        else
            g2.setPaint(bandcolor.darker());
        g2.fill(band);
    } else {
        super.drawRangeGridlines(g2, dataArea, ticks);
    }
    g2.setComposite(oldcomp);
}

From source file:ro.nextreports.engine.exporter.ResultExporter.java

protected byte[] getScaledImage(InputStream is, String name, int width, int height) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {//from   ww w  .  j  a  v a2  s  .c o m
        BufferedImage img = ImageIO.read(is);

        if ((img.getWidth() == width) && (img.getHeight() == height)) {
            // original width and height                
            ImageIO.write(img, "png", baos);
        } else {
            int type = img.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : img.getType();
            BufferedImage scaledImg = new BufferedImage(width, height, type);
            Graphics2D gScaledImg = scaledImg.createGraphics();

            gScaledImg.setComposite(AlphaComposite.Src);
            gScaledImg.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            gScaledImg.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

            gScaledImg.drawImage(img, 0, 0, width, height, null);

            ImageIO.write(scaledImg, "png", baos);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        LOG.error(ex.getMessage(), ex);
        throw new IOException("Image '" + name + "' could not be scaled.");
    } finally {
        is.close();
    }
    return baos.toByteArray();
}

From source file:genlab.gui.jfreechart.EnhancedSpiderWebPlot.java

/**
 * Draws the plot on a Java 2D graphics device (such as the screen or a
 * printer)./*from   ww w. j av  a 2  s .  co 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 a maximum value to use on the axes
        if (this.maxValue == DEFAULT_MAX_VALUE)
            calculateMaxValue(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 > 2 ? catCount : 3));

            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);
            drawLabel(g2, radarArea, 0.0, cat, angle, 360.0 / (catCount > 2 ? catCount : 3));
        }

        // 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);
}