Example usage for java.awt Graphics2D getTransform

List of usage examples for java.awt Graphics2D getTransform

Introduction

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

Prototype

public abstract AffineTransform getTransform();

Source Link

Document

Returns a copy of the current Transform in the Graphics2D context.

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();/*www.  j a v  a  2s  .  c  o  m*/
        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:net.sf.maltcms.chromaui.annotations.PeakAnnotationRenderer.java

private void drawEntity(Shape entity, Graphics2D g2, Color fill, Color stroke, ChartPanel chartPanel,
        boolean scale, float alpha) {
    if (entity != null) {
        //System.out.println("Drawing entity with bbox: "+entity.getBounds2D());
        Shape savedClip = g2.getClip();
        Rectangle2D dataArea = chartPanel.getScreenDataArea();
        Color c = g2.getColor();//from www . j  av a2  s.c o m
        Composite comp = g2.getComposite();
        g2.clip(dataArea);
        g2.setColor(fill);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        AffineTransform originalTransform = g2.getTransform();
        Shape transformed = entity;
        FlatteningPathIterator iter = new FlatteningPathIterator(
                transformed.getPathIterator(new AffineTransform()), 1);
        Path2D.Float path = new Path2D.Float();
        path.append(iter, false);
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
        g2.fill(path);
        if (stroke != null) {
            g2.setColor(stroke);
            g2.draw(path);
        }
        g2.setComposite(comp);
        g2.setColor(c);
        g2.setClip(savedClip);
    } else {
        Logger.getLogger(getClass().getName()).info("Entity is null!");
    }
}

From source file:com.epiq.bitshark.ui.FrequencyDomainMouseMarker.java

/**
 * Draws the annotation./*from   www.j  a va 2 s .  c  o m*/
 *
 * @param g2  the graphics device.
 * @param plot  the plot.
 * @param dataArea  the data area.
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param rendererIndex  the renderer index.
 * @param info  if supplied, this info object will be populated with
 *              entity information.
 */
@Override
public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis,
        int rendererIndex, PlotRenderingInfo info) {

    if (!visible) {
        return;
    }

    PlotOrientation orientation = plot.getOrientation();
    RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(plot.getDomainAxisLocation(), orientation);
    RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation(plot.getRangeAxisLocation(), orientation);
    float j2DX = (float) domainAxis.valueToJava2D(this.x, dataArea, domainEdge);
    float j2DY = (float) rangeAxis.valueToJava2D(this.y, dataArea, rangeEdge);
    Rectangle2D displayArea = new Rectangle2D.Double(j2DX - this.displayWidth / 2.0,
            j2DY - this.displayHeight / 2.0, this.displayWidth, this.displayHeight);

    // here we change the AffineTransform so we can draw the annotation
    // to a larger area and scale it down into the display area
    // afterwards, the original transform is restored
    AffineTransform savedTransform = g2.getTransform();
    Rectangle2D drawArea = new Rectangle2D.Double(0.0, 0.0, this.displayWidth * this.drawScaleFactor,
            this.displayHeight * this.drawScaleFactor);

    g2.scale(1 / this.drawScaleFactor, 1 / this.drawScaleFactor);
    g2.translate((j2DX - this.displayWidth / 2.0) * this.drawScaleFactor,
            (j2DY - this.displayHeight / 2.0) * this.drawScaleFactor);
    draw(g2, drawArea);
    g2.setTransform(savedTransform);
    String toolTip = getToolTipText();
    String url = getURL();
    if (toolTip != null || url != null) {
        addEntity(info, displayArea, rendererIndex, toolTip, url);
    }

}

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

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (getChart() == null) {
        return;//from  w w  w. ja v a 2 s. c  om
    }
    Graphics2D g2 = (Graphics2D) g.create();

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

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

    if (drawWidth < getMinimumDrawWidth()) {
        setChartFieldValue(getChartFieldByName("scaleX"), drawWidth / getMinimumDrawWidth());
        // this.scaleX = drawWidth / getMinimumDrawWidth();
        drawWidth = getMinimumDrawWidth();
        scale = true;
    } else if (drawWidth > getMaximumDrawWidth()) {
        setChartFieldValue(getChartFieldByName("scaleX"), drawWidth / getMaximumDrawWidth());
        // this.scaleX = drawWidth / getMaximumDrawWidth();
        drawWidth = getMaximumDrawWidth();
        scale = true;
    }

    if (drawHeight < getMinimumDrawHeight()) {
        setChartFieldValue(getChartFieldByName("scaleY"), drawHeight / getMinimumDrawHeight());
        // this.scaleY = drawHeight / getMinimumDrawHeight();
        drawHeight = getMinimumDrawHeight();
        scale = true;
    } else if (drawHeight > getMaximumDrawHeight()) {
        setChartFieldValue(getChartFieldByName("scaleY"), drawHeight / getMaximumDrawHeight());
        // this.scaleY = drawHeight / getMaximumDrawHeight();
        drawHeight = getMaximumDrawHeight();
        scale = true;
    }

    Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth, drawHeight);

    // are we using the chart buffer?
    if ((Boolean) getChartFieldValueByName("useBuffer")) {

        // do we need to resize the buffer?
        if ((getChartFieldValueByName("chartBuffer") == null)
                || ((Integer) getChartFieldValueByName("chartBufferWidth") != available.getWidth())
                || ((Integer) getChartFieldValueByName("chartBufferHeight") != available.getHeight())) {
            setChartFieldValue(getChartFieldByName("chartBufferWidth"), (int) available.getWidth());
            // this.chartBufferWidth = (int) available.getWidth();
            setChartFieldValue(getChartFieldByName("chartBufferHeight"), (int) available.getHeight());
            // this.chartBufferHeight = (int) available.getHeight();
            GraphicsConfiguration gc = g2.getDeviceConfiguration();
            setChartFieldValue(getChartFieldByName("chartBuffer"),
                    gc.createCompatibleImage((Integer) getChartFieldValueByName("chartBufferWidth"),
                            (Integer) getChartFieldValueByName("chartBufferHeight"), Transparency.TRANSLUCENT));
            // this.chartBuffer = gc.createCompatibleImage(this.chartBufferWidth,
            // this.chartBufferHeight, Transparency.TRANSLUCENT);
            setRefreshBuffer(true);
        }

        // do we need to redraw the buffer?
        if (getRefreshBuffer()) {

            setRefreshBuffer(false); // clear the flag

            Rectangle2D bufferArea = new Rectangle2D.Double(0, 0,
                    (Integer) getChartFieldValueByName("chartBufferWidth"),
                    (Integer) getChartFieldValueByName("chartBufferHeight"));

            Graphics2D bufferG2 = (Graphics2D) ((Image) getChartFieldValueByName("chartBuffer")).getGraphics();
            Rectangle r = new Rectangle(0, 0, (Integer) getChartFieldValueByName("chartBufferWidth"),
                    (Integer) getChartFieldValueByName("chartBufferHeight"));
            bufferG2.setPaint(getBackground());
            bufferG2.fill(r);
            if (scale) {
                AffineTransform saved = bufferG2.getTransform();
                AffineTransform st = AffineTransform.getScaleInstance(
                        (Double) getChartFieldValueByName("scaleX"),
                        (Double) getChartFieldValueByName("scaleY"));
                bufferG2.transform(st);
                getChart().draw(bufferG2, chartArea, getAnchor(), getChartRenderingInfo());
                bufferG2.setTransform(saved);
            } else {
                getChart().draw(bufferG2, bufferArea, getAnchor(), getChartRenderingInfo());
            }

        }

        // zap the buffer onto the panel...
        g2.drawImage((Image) getChartFieldValueByName("chartBuffer"), insets.left, insets.top, this);

    }

    // or redrawing the chart every time...
    else {

        AffineTransform saved = g2.getTransform();
        g2.translate(insets.left, insets.top);
        if (scale) {
            AffineTransform st = AffineTransform.getScaleInstance((Double) getChartFieldValueByName("scaleX"),
                    (Double) getChartFieldValueByName("scaleY"));
            g2.transform(st);
        }
        getChart().draw(g2, chartArea, getAnchor(), getChartRenderingInfo());
        g2.setTransform(saved);

    }

    Iterator iterator = ((List) getChartFieldValueByName("overlays")).iterator();
    while (iterator.hasNext()) {
        Overlay overlay = (Overlay) iterator.next();
        overlay.paintOverlay(g2, this);
    }

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

    g2.dispose();

    setAnchor(null);
    setVerticalTraceLine(null);
    setHorizontalTraceLine(null);
}

From source file:org.gvsig.remotesensing.scatterplot.chart.ScatterPlotDiagram.java

/**
 * Paints the component by drawing the chart to fill the entire component,
 * but allowing for the insets (which will be non-zero if a border has been
 * set for this component).  To increase performance (at the expense of
 * memory), an off-screen buffer image can be used.
 *
 * @param g  the graphics device for drawing on.
 *///from  w  w w. ja v a2s.  co m
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (this.chart == null) {
        return;
    }
    Graphics2D g2 = (Graphics2D) g.create();

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

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

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

    Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth, drawHeight);

    // are we using the chart buffer?
    if (this.useBuffer) {

        // if buffer is being refreshed, it needs clearing unless it is
        // new - use the following flag to track this...
        boolean clearBuffer = true;

        // do we need to resize the buffer?
        if ((this.chartBuffer == null) || (this.chartBufferWidth != available.getWidth())
                || (this.chartBufferHeight != available.getHeight())) {
            this.chartBufferWidth = (int) available.getWidth();
            this.chartBufferHeight = (int) available.getHeight();
            this.chartBuffer = createImage(this.chartBufferWidth, this.chartBufferHeight);
            //                GraphicsConfiguration gc = g2.getDeviceConfiguration();
            //                this.chartBuffer = gc.createCompatibleImage(
            //                        this.chartBufferWidth, this.chartBufferHeight, 
            //                        Transparency.TRANSLUCENT);
            this.refreshBuffer = true;
            clearBuffer = false; // buffer is new, no clearing required
        }

        // do we need to redraw the buffer?
        if (this.refreshBuffer) {

            this.refreshBuffer = false; // clear the flag

            Rectangle2D bufferArea = new Rectangle2D.Double(0, 0, this.chartBufferWidth,
                    this.chartBufferHeight);

            Graphics2D bufferG2 = (Graphics2D) this.chartBuffer.getGraphics();
            if (clearBuffer) {
                bufferG2.clearRect(0, 0, this.chartBufferWidth, this.chartBufferHeight);
            }
            if (scale) {
                AffineTransform saved = bufferG2.getTransform();
                AffineTransform st = AffineTransform.getScaleInstance(this.scaleX, this.scaleY);
                bufferG2.transform(st);
                this.chart.draw(bufferG2, chartArea, this.anchor, this.info);
                bufferG2.setTransform(saved);
            } else {
                this.chart.draw(bufferG2, bufferArea, this.anchor, this.info);
            }
        }
        g2.drawImage(this.chartBuffer, insets.left, insets.top, this);
        g2.draw((Shape) activeROI.getShapesList().get(1));
        // Dibujar las rois que se encuentren activas

    }

    // or redrawing the chart every time...
    else {

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

        // Se pintan las Roi activa
        drawsROIs(g2);
        g2.setTransform(saved);
    }

    g2.dispose();
    this.anchor = null;
}

From source file:MWC.GUI.JFreeChart.StepperChartPanel.java

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

    final Graphics2D g2 = (Graphics2D) g;

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

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

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

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

    chartArea.setRect(0.0, 0.0, drawWidth, drawHeight);

    final AffineTransform saved = g2.getTransform();
    g2.translate(insets.left, insets.right);
    if (scale) {
        final AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);
        g2.transform(st);
    }
    getChart().draw(g2, chartArea, this.getChartRenderingInfo());
    g2.setTransform(saved);

}

From source file:com.github.lindenb.jvarkit.tools.misc.BamCmpCoverage.java

@Override
public Collection<Throwable> call() throws Exception {

    if (getOutputFile() == null) {
        return wrapException("output image file not defined");
    }/*ww w .  j  a v  a2 s  .  com*/

    if (this.imgageSize < 1) {
        return wrapException("Bad image size:" + this.imgageSize);
    }

    if (this.minDepth < 0) {
        return wrapException("Bad min depth : " + this.minDepth);
    }
    if (this.minDepth >= this.maxDepth) {
        return wrapException("Bad min<max depth : " + this.minDepth + "<" + this.maxDepth);
    }

    if (this.getBedFile() != null) {
        readBedFile(this.getBedFile());
    }

    if (regionStr != null && this.intervals != null) {
        return wrapException("bed and interval both defined.");
    }

    final SamRecordFilter filter = new SamRecordFilter() {
        @Override
        public boolean filterOut(SAMRecord first, SAMRecord second) {
            return filterOut(first);
        }

        @Override
        public boolean filterOut(SAMRecord rec) {
            if (rec.getReadUnmappedFlag())
                return true;
            if (rec.isSecondaryOrSupplementary())
                return true;
            if (rec.getDuplicateReadFlag())
                return true;
            if (rec.getNotPrimaryAlignmentFlag())
                return true;
            if (rec.getReadFailsVendorQualityCheckFlag())
                return true;
            if (rec.getMappingQuality() == 0)
                return true;
            /* ignore non-overlapping BED, already checked with QuertInterval 
            if( intervals!=null &&
               ! intervals.containsOverlapping(
               new Interval(rec.getReferenceName(),
             rec.getAlignmentStart(),
             rec.getAlignmentEnd()))
             )
               {
               return true;
               }
               */

            return false;
        }
    };
    Set<File> files = new HashSet<File>();
    try {

        SamReaderFactory srf = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT);
        srf.disable(SamReaderFactory.Option.EAGERLY_DECODE);
        srf.disable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS);
        srf.disable(SamReaderFactory.Option.VALIDATE_CRC_CHECKSUMS);
        final List<String> args = this.getInputFiles();
        for (String arg : args) {
            File f = new File(arg);
            if (f.getName().endsWith(".list")) {
                LOG.info("Reading BAM list from " + f);
                BufferedReader in = IOUtils.openFileForBufferedReading(f);
                String line;
                while ((line = in.readLine()) != null) {
                    if (line.trim().isEmpty() || line.startsWith("#"))
                        continue;
                    files.add(new File(line));
                }
                in.close();
            } else {
                files.add(f);
            }
        }
        if (files.isEmpty()) {
            return wrapException("No BAM defined");
        }

        Comparator<SAMRecord> comparator = new Comparator<SAMRecord>() {
            @Override
            public int compare(SAMRecord samRecord1, SAMRecord samRecord2) {
                final int refIndex1 = samRecord1.getReferenceIndex();
                final int refIndex2 = samRecord2.getReferenceIndex();
                if (refIndex1 == -1) {
                    return (refIndex2 == -1 ? 0 : 1);
                } else if (refIndex2 == -1) {
                    return -1;
                }
                final int cmp = refIndex1 - refIndex2;
                if (cmp != 0) {
                    return cmp;
                }
                return samRecord1.getAlignmentStart() - samRecord2.getAlignmentStart();
            }
        };
        List<SamReader> readers = new ArrayList<SamReader>(files.size());
        List<CloseableIterator<SAMRecord>> iterators = new ArrayList<CloseableIterator<SAMRecord>>(
                files.size());

        Set<String> samples = new TreeSet<String>();
        SAMSequenceDictionary dict = null;

        /* will be initialized below once, if needed */
        QueryInterval queryIntervalArray[] = null;

        //scan samples names
        for (File bamFile : files) {
            SamReader r = srf.open(bamFile);
            readers.add(r);

            SAMFileHeader h = r.getFileHeader();
            if (h.getSortOrder() != SortOrder.coordinate) {
                r.close();
                return wrapException("file " + bamFile + " not sorted on coordinate");
            }
            if (dict == null) {
                dict = h.getSequenceDictionary();
            } else if (!SequenceUtil.areSequenceDictionariesEqual(dict, h.getSequenceDictionary())) {
                return wrapException("Found more than one dictint sequence dictionary");
            }

            //fill query interval once
            List<QueryInterval> queryIntervals = new ArrayList<>();
            if (regionStr != null && queryIntervalArray == null) {
                int colon = regionStr.indexOf(':');
                String chrom;
                int chromStart;
                int chromEnd;

                if (colon == -1) {
                    chrom = regionStr;
                } else {
                    chrom = regionStr.substring(0, colon);
                }

                SAMSequenceRecord ssr = dict.getSequence(chrom);
                if (ssr == null) {
                    return wrapException("Chromosome " + chrom + " not present in dictionary");
                }
                int hyphen = regionStr.indexOf('-', colon + 1);
                if (hyphen != -1) {
                    chromStart = Integer.parseInt(regionStr.substring(colon + 1, hyphen));
                    chromEnd = Integer.parseInt(regionStr.substring(hyphen + 1));
                } else {
                    chromStart = 0;
                    chromEnd = ssr.getSequenceLength() - 1;
                }
                if (chromStart < 0 || chromEnd < chromStart) {
                    return wrapException("bad position in " + regionStr);
                }

                queryIntervals.add(new QueryInterval(ssr.getSequenceIndex(), chromStart, chromEnd));
            }

            if (this.intervals != null && queryIntervalArray == null) {
                for (Interval interval : this.intervals.keySet()) {
                    SAMSequenceRecord ssr = dict.getSequence(interval.getContig());
                    if (ssr == null) {
                        return wrapException(
                                "Chromosome " + interval.getContig() + " not present in dictionary");
                    }
                    queryIntervals.add(
                            new QueryInterval(ssr.getSequenceIndex(), interval.getStart(), interval.getEnd()));
                }
            }

            if (!queryIntervals.isEmpty() && queryIntervalArray == null) {
                Collections.sort(queryIntervals);
                queryIntervalArray = queryIntervals.toArray(new QueryInterval[queryIntervals.size()]);
            }

            for (SAMReadGroupRecord rg : h.getReadGroups()) {
                String sample = rg.getSample();
                if (sample == null)
                    continue;
                samples.add(sample);
            }
            CloseableIterator<SAMRecord> reciterator = null;
            if (queryIntervalArray == null) {
                reciterator = r.iterator();
            } else {
                reciterator = r.query(queryIntervalArray, false);
            }

            reciterator = new FilteringIterator(reciterator, filter);
            iterators.add(reciterator);
        }
        //free GC
        queryIntervalArray = null;

        LOG.info("Samples:" + samples.size());
        for (String sample : samples) {
            this.sample2column.put(sample, this.sample2column.size());
        }

        //create merging sam-reader
        MergingSamRecordIterator iter = new MergingSamRecordIterator(comparator, iterators);

        //create image
        LOG.info("Creating image " + this.imgageSize + "x" + this.imgageSize);
        this.image = new BufferedImage(this.imgageSize, this.imgageSize, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = this.image.createGraphics();
        this.marginWidth = this.imgageSize * 0.05;
        double drawingWidth = (this.imgageSize - 1) - marginWidth;
        this.sampleWidth = drawingWidth / samples.size();
        //g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, this.imgageSize, this.imgageSize);
        g.setColor(Color.BLACK);
        Hershey hershey = new Hershey();
        for (String sample_x : samples) {
            double labelHeight = marginWidth;
            if (labelHeight > 50)
                labelHeight = 50;

            g.setColor(Color.BLACK);
            hershey.paint(g, sample_x, marginWidth + sample2column.get(sample_x) * sampleWidth,
                    marginWidth - labelHeight, sampleWidth * 0.9, labelHeight * 0.9);

            AffineTransform old = g.getTransform();
            AffineTransform tr = AffineTransform.getTranslateInstance(marginWidth,
                    marginWidth + sample2column.get(sample_x) * sampleWidth);
            tr.rotate(Math.PI / 2);
            g.setTransform(tr);
            hershey.paint(g, sample_x, 0.0, 0.0, sampleWidth * 0.9, labelHeight * 0.9); //g.drawString(this.tabixFile.getFile().getName(),0,0);
            g.setTransform(old);

            for (String sample_y : samples) {

                Rectangle2D rect = new Rectangle2D.Double(
                        marginWidth + sample2column.get(sample_x) * sampleWidth,
                        marginWidth + sample2column.get(sample_y) * sampleWidth, sampleWidth, sampleWidth);
                g.setColor(Color.BLUE);
                g.draw(new Line2D.Double(rect.getMinX(), rect.getMinY(), rect.getMaxX(), rect.getMaxY()));
                g.setColor(Color.BLACK);
                g.draw(rect);
            }
        }

        //ceate bit-array
        BitSampleMatrix bitMatrix = new BitSampleMatrix(samples.size());

        //preivous chrom
        //int prev_tid=-1;
        BufferedList<Depth> depthList = new BufferedList<Depth>();
        g.setColor(Color.BLACK);
        SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(dict);
        LOG.info("Scanning bams...");
        while (iter.hasNext()) {
            SAMRecord rec = iter.next();
            if (filter.filterOut(rec))
                continue;
            progress.watch(rec);

            SAMReadGroupRecord gr = rec.getReadGroup();
            if (gr == null)
                continue;
            String sample = gr.getSample();
            if (sample == null)
                continue;
            int sample_id = this.sample2column.get(sample);

            Cigar cigar = rec.getCigar();
            if (cigar == null)
                continue;
            int refPos = rec.getAlignmentStart();

            /* cleanup front pos */
            while (!depthList.isEmpty()) {
                Depth front = depthList.getFirst();

                if (front.tid != rec.getReferenceIndex().intValue() || front.pos < refPos) {
                    paint(bitMatrix, front);
                    depthList.removeFirst();
                    continue;
                } else {
                    break;
                }
            }

            for (CigarElement ce : cigar.getCigarElements()) {
                CigarOperator op = ce.getOperator();
                if (!op.consumesReferenceBases())
                    continue;
                if (op.consumesReadBases()) {
                    for (int i = 0; i < ce.getLength(); ++i) {
                        Depth depth = null;
                        int pos = refPos + i;

                        //ignore non-overlapping BED
                        if (this.intervals != null && !this.intervals
                                .containsOverlapping(new Interval(rec.getReferenceName(), pos, pos))) {
                            continue;
                        } else if (depthList.isEmpty()) {
                            depth = new Depth();
                            depth.pos = pos;
                            depth.tid = rec.getReferenceIndex();
                            depthList.add(depth);
                        } else if (depthList.getLast().pos < pos) {
                            Depth prev = depthList.getLast();

                            while (prev.pos < pos) {
                                depth = new Depth();
                                depth.pos = prev.pos + 1;
                                depth.tid = rec.getReferenceIndex();
                                depthList.add(depth);
                                prev = depth;
                            }
                            depth = prev;
                        }

                        else {
                            int lastPos = depthList.get(depthList.size() - 1).pos;
                            int distance = lastPos - pos;
                            int indexInList = (depthList.size() - 1) - (distance);
                            if (indexInList < 0) {
                                //can appen when BED declared and partially overlap the read
                                continue;
                            }

                            depth = depthList.get((depthList.size() - 1) - (distance));
                            if (depth.pos != pos) {
                                return wrapException(" " + pos + " vs " + depth.pos + " " + lastPos);
                            }
                        }
                        depth.depths[sample_id]++;
                    }
                }
                refPos += ce.getLength();
            }
        }
        while (!depthList.isEmpty()) {
            //paint(g,depthList.remove(0));
            paint(bitMatrix, depthList.remove(0));
        }
        progress.finish();
        iter.close();

        //paint bitset

        for (int x = 0; x < bitMatrix.n_samples; ++x) {
            for (int y = 0; y < bitMatrix.n_samples; ++y) {
                LOG.info("Painting...(" + x + "/" + y + ")");
                paint(g, bitMatrix.get(x, y));
            }
        }

        g.dispose();
        //close readers
        for (SamReader r : readers)
            r.close();

        //save file
        LOG.info("saving " + getOutputFile());
        if (getOutputFile().getName().toLowerCase().endsWith(".png")) {
            ImageIO.write(this.image, "PNG", getOutputFile());
        } else {
            ImageIO.write(this.image, "JPG", getOutputFile());
        }

        return Collections.emptyList();
    } catch (Exception err) {
        return wrapException(err);
    } finally {

    }
}

From source file:cn.pholance.datamanager.common.components.JRViewer.java

protected void paintPageError(Graphics2D grx) {
    AffineTransform origTransform = grx.getTransform();

    AffineTransform transform = new AffineTransform();
    transform.translate(1, 1);//from  w ww  .j  a va  2 s  .c  om
    transform.scale(realZoom, realZoom);
    grx.transform(transform);

    try {
        drawPageError(grx);
    } finally {
        grx.setTransform(origTransform);
    }
}

From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java

/**
 * Labels the specified non-self-loop edge with the specified label.
 * Uses the font specified by this instance's 
 * <code>EdgeFontFunction</code>.  (If the font is unspecified, the existing
 * font for the graphics context is used.)  Positions the 
 * label between the endpoints according to the coefficient returned
 * by this instance's edge label closeness function.
 *//*  w  ww .  ja v a2  s.  c om*/
protected void labelEdge(Graphics2D g2d, Edge e, String label, int x1, int x2, int y1, int y2) {
    int distX = x2 - x1;
    int distY = y2 - y1;
    double totalLength = Math.sqrt(distX * distX + distY * distY);

    double closeness = edgeLabelClosenessFunction.getNumber(e).doubleValue();

    int posX = (int) (x1 + (closeness) * distX);
    int posY = (int) (y1 + (closeness) * distY);

    int xDisplacement = (int) (LABEL_OFFSET * (distY / totalLength));
    int yDisplacement = (int) (LABEL_OFFSET * (-distX / totalLength));

    Component component = prepareRenderer(graphLabelRenderer, label, isPicked(e), e);

    Dimension d = component.getPreferredSize();

    Shape edgeShape = edgeShapeFunction.getShape(e);

    double parallelOffset = 1;

    parallelOffset += parallelEdgeIndexFunction.getIndex(e);

    if (edgeShape instanceof Ellipse2D) {
        parallelOffset += edgeShape.getBounds().getHeight();
        parallelOffset = -parallelOffset;
    }

    parallelOffset *= d.height;

    AffineTransform old = g2d.getTransform();
    AffineTransform xform = new AffineTransform(old);
    xform.translate(posX + xDisplacement, posY + yDisplacement);
    double dx = x2 - x1;
    double dy = y2 - y1;
    if (graphLabelRenderer.isRotateEdgeLabels()) {
        double theta = Math.atan2(dy, dx);
        if (dx < 0) {
            theta += Math.PI;
        }
        xform.rotate(theta);
    }
    if (dx < 0) {
        parallelOffset = -parallelOffset;
    }

    xform.translate(-d.width / 2, -(d.height / 2 - parallelOffset));
    g2d.setTransform(xform);
    rendererPane.paintComponent(g2d, component, screenDevice, 0, 0, d.width, d.height, true);
    g2d.setTransform(old);
}

From source file:forseti.JUtil.java

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

    return (imagenMensaje);
}