Example usage for java.awt AlphaComposite SRC_OVER

List of usage examples for java.awt AlphaComposite SRC_OVER

Introduction

In this page you can find the example usage for java.awt AlphaComposite SRC_OVER.

Prototype

int SRC_OVER

To view the source code for java.awt AlphaComposite SRC_OVER.

Click Source Link

Document

The source is composited over the destination (Porter-Duff Source Over Destination rule).

Usage

From source file:de.tor.tribes.ui.algo.TimeFrameVisualizer.java

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (mTimeFrame == null) {
        renderNoInfoView(g);//from   w ww .ja va 2  s. c o m
    } else {
        updateSize();
        LongRange startRange = mTimeFrame.getStartRange();
        LongRange arriveRange = mTimeFrame.getArriveRange();
        HashMap<LongRange, TimeSpan> startRanges = mTimeFrame
                .startTimespansToRangesMap(AnyTribe.getSingleton());
        HashMap<LongRange, TimeSpan> arriveRanges = mTimeFrame.arriveTimespansToRangesMap(null);
        long minValue = startRange.getMinimumLong();
        long maxValue = arriveRange.getMaximumLong();
        Graphics2D g2d = (Graphics2D) g;
        g2d.setPaint(new TexturePaint(STROKED, new Rectangle(0, 0, 3, 3)));
        g2d.fillRect(0, 0, getWidth(), getHeight());

        //draw frame around the entire range
        renderRange(new LongRange(startRange.getMinimumLong(), arriveRange.getMaximumLong()), startRange,
                arriveRange, false, false, g2d, null, popupInfo);
        g2d.setColor(Constants.DS_BACK);
        popupInfo.clear();
        //fill start range
        renderRange(startRange, startRange, arriveRange, true, false, g2d, null, popupInfo);
        //fill arrive range
        renderRange(arriveRange, startRange, arriveRange, false, true, g2d, null, popupInfo);
        Paint p = g2d.getPaint();
        Iterator<LongRange> rangeKeys = startRanges.keySet().iterator();
        while (rangeKeys.hasNext()) {
            LongRange currentRange = rangeKeys.next();

            TimeSpan spanForRange = startRanges.get(currentRange);
            if (spanForRange != null) {
                if (spanForRange.isValidAtEveryDay()) {
                    g2d.setPaint(new TexturePaint(DAILY_START_FRAME_FILL, new Rectangle(0, 0, 3, 3)));
                } else if (spanForRange.isValidAtExactTime()) {
                    g2d.setPaint(new TexturePaint(EXACT_START_FRAME_FILL, new Rectangle(0, 0, 3, 3)));
                } else {
                    g2d.setPaint(new TexturePaint(ONE_DAY_START_FRAME_FILL, new Rectangle(0, 0, 3, 3)));
                }
            }
            renderRange(currentRange, startRange, arriveRange, false, false, g2d, spanForRange, popupInfo);
        }

        Composite c = g2d.getComposite();
        rangeKeys = arriveRanges.keySet().iterator();
        while (rangeKeys.hasNext()) {
            LongRange currentRange = rangeKeys.next();
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
            g2d.setPaint(new TexturePaint(ARRIVE_FRAME_FILL, new Rectangle(0, 0, 3, 3)));
            TimeSpan spanForRange = arriveRanges.get(currentRange);
            renderRange(currentRange, startRange, arriveRange, false, false, g2d, spanForRange, popupInfo);
        }
        g2d.setComposite(c);
        g2d.setPaint(p);
        renderDayMarkers(minValue, maxValue, g2d);
        renderPopup(popupInfo, g2d);
    }
}

From source file:org.openmeetings.app.data.record.BatikMethods.java

public void drawThickLine2D(Graphics2D g2d, double x1, double y1, double x2, double y2, int width, Color c,
        double xObj, double yObj, float alpha) throws Exception {
    g2d.setPaint(c);/*from  w w w.  ja  v  a  2s .com*/

    int[] rules = new int[8];

    //all possible Compositing Rules:
    rules[0] = AlphaComposite.SRC_OVER;
    rules[1] = AlphaComposite.DST_OVER;
    rules[2] = AlphaComposite.CLEAR;
    rules[3] = AlphaComposite.SRC;
    rules[4] = AlphaComposite.SRC_IN;
    rules[5] = AlphaComposite.DST_IN;
    rules[6] = AlphaComposite.SRC_OUT;
    rules[7] = AlphaComposite.DST_OUT;

    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, alpha));
    g2d.setStroke(new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    Line2D line = new Line2D.Double(x1 + xObj, y1 + yObj, x2 + xObj, y2 + yObj);
    g2d.draw(line);
}

From source file:org.tsho.dmc2.core.chart.AbstractDmcPlot.java

public void drawPlot(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info) {
    Object originalAntialiasHint = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);

    if (plotAntialias) {
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    } else {//  w ww . j  av  a  2  s.c  om
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
    }

    Composite originalComposite = g2.getComposite();
    if (alpha == true) {
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha()));
    }

    /* if automatic bounds... */
    if (!isNoData()) {
        if (this instanceof DmcRenderablePlot) {
            DmcPlotRenderer renderer;
            renderer = ((DmcRenderablePlot) this).getPlotRenderer();
            if (renderer != null) {
                renderer.initialize();
            }
        }
    }

    g2.setStroke(stroke);
    g2.setPaint(paint);
    render(g2, dataArea, info); /** This is where the computations method is called.*/
    g2.setComposite(originalComposite);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, originalAntialiasHint);
}

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 {//ww  w  .  j  a  v a 2s  . 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: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 {//w w w. j av  a  2 s  .c o m
        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.controlj.addon.gwttree.server.OpaqueBarRenderer3D.java

@Override
public void drawBackground(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea) {

    float x0 = (float) dataArea.getX();
    float x1 = x0 + (float) Math.abs(getXOffset());
    float x3 = (float) dataArea.getMaxX();
    float x2 = x3 - (float) Math.abs(getXOffset());

    float y0 = (float) dataArea.getMaxY();
    float y1 = y0 - (float) Math.abs(getYOffset());
    float y3 = (float) dataArea.getMinY();
    float y2 = y3 + (float) Math.abs(getYOffset());

    GeneralPath clip = new GeneralPath();
    clip.moveTo(x0, y0);/*  w  ww  . ja  v  a2  s  .  co m*/
    clip.lineTo(x0, y2);
    clip.lineTo(x1, y3);
    clip.lineTo(x3, y3);
    clip.lineTo(x3, y1);
    clip.lineTo(x2, y0);
    clip.closePath();

    Composite originalComposite = g2.getComposite();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, plot.getBackgroundAlpha()));

    // fill background...
    Paint backgroundPaint = plot.getBackgroundPaint();
    if (backgroundPaint != null) {
        g2.setPaint(backgroundPaint);
        g2.fill(clip);
    }

    GeneralPath bottomWall = new GeneralPath();
    bottomWall.moveTo(x0, y0);
    bottomWall.lineTo(x1, y1);
    bottomWall.lineTo(x3, y1);
    bottomWall.lineTo(x2, y0);
    bottomWall.closePath();
    g2.setPaint(getWallPaint());
    g2.fill(bottomWall);

    // draw background image, if there is one...
    Image backgroundImage = plot.getBackgroundImage();
    if (backgroundImage != null) {
        Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX() + getXOffset(), dataArea.getY(),
                dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset());
        plot.drawBackgroundImage(g2, adjusted);
    }

    g2.setComposite(originalComposite);

}

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;//  w w  w . jav a2s  . c  o m

    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:net.sourceforge.processdash.ui.lib.chart.DiscPlot.java

@Override
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState,
        PlotRenderingInfo info) {/*from   w w  w  .j a  va2  s . co m*/

    // 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 (!getDiscDistributor().isDatasetEmpty()) {
        Rectangle2D dataArea = getDataArea(area);
        drawDiscs(g2, dataArea, info);
        drawLegendAxis(g2, dataArea, info);
    } else {
        drawNoDataMessage(g2, area);
    }

    g2.setClip(savedClip);
    g2.setComposite(originalComposite);

    drawOutline(g2, area);
}

From source file:SWTGraphics2D.java

/**
 * Sets the current color for this graphics context.
 *
 * @param color  the color./*from  ww  w  .ja v  a 2s .c  o m*/
 *
 * @see #getColor()
 */
public void setColor(Color color) {
    org.eclipse.swt.graphics.Color swtColor = getSwtColorFromPool(color);
    this.gc.setForeground(swtColor);
    // handle transparency and compositing.
    if (this.composite instanceof AlphaComposite) {
        AlphaComposite acomp = (AlphaComposite) this.composite;
        switch (acomp.getRule()) {
        case AlphaComposite.SRC_OVER:
            this.gc.setAlpha((int) (color.getAlpha() * acomp.getAlpha()));
            break;
        default:
            this.gc.setAlpha(color.getAlpha());
            break;
        }
    }
}

From source file:dbseer.gui.panel.DBSeerExplainChartPanel.java

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;

    selectRectangle = new Rectangle2D.Double(x, y, width, height);
    g2d.setPaint(Color.black);/*  w  w  w.java2  s .c  om*/
    Composite c = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .4f);
    g2d.setComposite(c);
    g2d.fill(selectRectangle);
}