Example usage for java.awt Graphics2D fillRect

List of usage examples for java.awt Graphics2D fillRect

Introduction

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

Prototype

public abstract void fillRect(int x, int y, int width, int height);

Source Link

Document

Fills the specified rectangle.

Usage

From source file:org.squidy.designer.components.versioning.Versioning.java

@Override
protected void paintShape(PPaintContext paintContext) {
    super.paintShape(paintContext);

    Graphics2D g = paintContext.getGraphics();

    PBounds bounds = getBoundsReference();
    double x = bounds.getX();
    double y = bounds.getY();
    double width = bounds.getWidth();
    double height = bounds.getHeight();

    //      g.setColor(Color.RED);
    //      g.draw(bounds);

    g.setClip(bounds);//from  w  ww  .  j av  a2s .  co  m

    for (int i = 0; i < 7; i++) {
        PAffineTransform transform = new PAffineTransform();
        transform.scale(0.12, 0.12);
        transform.translate(i * 122, 0);

        paintContext.pushTransform(transform);

        if (!isRenderPrimitive()) {
            versionNode.fullPaint(paintContext);
        }

        if (i == 6) {
            g.setStroke(StrokeUtils.getBasicStroke(5f));
            g.setColor(Color.GRAY);
            if (isRenderPrimitiveRect())
                g.drawRect((int) x, (int) y, 100, (int) (height / 0.12));
            else
                g.drawRoundRect((int) x, (int) y, 100, (int) (height / 0.12), 15, 15);

            g.setColor(COLOR_FILL);
            if (isRenderPrimitiveRect())
                g.fillRect((int) x, (int) y, 100, (int) (height / 0.12));
            else
                g.fillRoundRect((int) x, (int) y, 100, (int) (height / 0.12), 15, 15);
        }

        paintContext.popTransform(transform);
    }

    g.setClip(null);
}

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");
    }//from  w w  w .  java 2  s .c  om

    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:LineStyles.java

/** This method draws the example figure */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;
    // Use anti-aliasing to avoid "jaggies" in the lines
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // Define the shape to draw
    GeneralPath shape = new GeneralPath();
    shape.moveTo(xpoints[0], ypoints[0]); // start at point 0
    shape.lineTo(xpoints[1], ypoints[1]); // draw a line to point 1
    shape.lineTo(xpoints[2], ypoints[2]); // and then on to point 2

    // Move the origin to the right and down, creating a margin
    g.translate(20, 40);//ww  w. j  av  a2 s. c  o m

    // Now loop, drawing our shape with the three different line styles
    for (int i = 0; i < linestyles.length; i++) {
        g.setColor(Color.gray); // Draw a gray line
        g.setStroke(linestyles[i]); // Select the line style to use
        g.draw(shape); // Draw the shape

        g.setColor(Color.black); // Now use black
        g.setStroke(thindashed); // And the thin dashed line
        g.draw(shape); // And draw the shape again.

        // Highlight the location of the vertexes of the shape
        // This accentuates the cap and join styles we're demonstrating
        for (int j = 0; j < xpoints.length; j++)
            g.fillRect(xpoints[j] - 2, ypoints[j] - 2, 5, 5);

        g.drawString(capNames[i], 5, 105); // Label the cap style
        g.drawString(joinNames[i], 5, 120); // Label the join style

        g.translate(150, 0); // Move over to the right before looping again
    }
}

From source file:org.csml.tommo.sugar.modules.QualityHeatMapsPerTileAndBase.java

private void writeImage2HTML(HTMLReportArchive report, LaneCoordinates laneCoordinates,
        TileNumeration tileNumeration) throws IOException {
    final ResultsTableModel model = new ResultsTableModel(this, laneCoordinates, tileNumeration);

    ZipOutputStream zip = report.zipFile();
    StringBuffer b = report.htmlDocument();
    StringBuffer d = report.dataDocument();

    int imgSize = Options.getHeatmapImageSize() + 1; // add one pixel for internal grid
    int width = imgSize * model.getColumnCount() + 1; // add one pixel for left border
    int topBottomSeparator = 50;
    if (model.getTopBottomSeparatorColumn() > 0) {
        width += topBottomSeparator; // add top bottom separator
    }/*from ww  w.  j a  v  a  2 s.c o  m*/
    int height = imgSize * model.getRowCount() + 1; // add one pixel for top border
    int yOffset = 10 * model.getTileNumeration().getCycleSize(); // space for column header
    int xOffset = 20; // space for row header
    BufferedImage fullImage = new BufferedImage(width + xOffset, height + yOffset, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) fullImage.getGraphics();
    Color headerBackground = new Color(0x00, 0x00, 0x80);
    Color headerForeground = Color.WHITE;

    // Do the headers
    d.append("#Tiles: ");

    d.append("\t");
    g2.setColor(headerBackground);
    g2.fillRect(0, height, width + xOffset, yOffset);
    g2.fillRect(width, 0, xOffset, height + yOffset);
    g2.setColor(headerForeground);
    g2.setFont(g2.getFont().deriveFont(7f).deriveFont(Font.BOLD));
    drawColumnHeader(g2, model, imgSize, topBottomSeparator, height, d);

    g2.setFont(g2.getFont().deriveFont(9f).deriveFont(Font.BOLD));
    drawRowHeader(g2, model, imgSize, width, xOffset);

    long before = System.currentTimeMillis();

    for (int r = 0; r < model.getRowCount(); r++) {

        int separator = 0;
        // "header" for base position number
        for (int c = 0; c < model.getColumnCount(); c++) {
            TileBPCoordinates tileBPCoordinate = model.getCoordinateAt(r, c);
            MeanQualityMatrix matrix = getMeanQualityMatrix(tileBPCoordinate);

            if (matrix != null) {
                BufferedImage image = (BufferedImage) matrix.createBufferedImage(LinearPaintScale.PAINT_SCALE);
                g2.drawImage(image, 1 + imgSize * c + separator, 1 + imgSize * r, imgSize * (c + 1) + separator,
                        imgSize * (r + 1), 0, 0, image.getWidth(), image.getHeight(), null);
            } else {
                d.append("Missing matrix for: " + tileBPCoordinate + "\n");
            }
            if (c == model.getTopBottomSeparatorColumn()) {
                separator = topBottomSeparator;
            }
        }
    }

    g2.dispose();

    String imgFileName = "matrix_" + laneCoordinates.getFlowCell() + "_" + laneCoordinates.getLane() + ".png";
    zip.putNextEntry(new ZipEntry(report.folderName() + "/Images/" + imgFileName));
    ImageIO.write(fullImage, "png", zip);
    b.append("<img src=\"Images/" + imgFileName + "\" alt=\"full image\">\n");

    // #38: Save each mean value of tile as a matrix file e.g. CSV file format
    writeCSVFile(report, laneCoordinates, tileNumeration, model);

    long after = System.currentTimeMillis();
    d.append("Creating report time: " + (after - before));

}

From source file:com.github.andreax79.meca.Main.java

public static Stats drawRule(int ruleNumber, int size, Boundaries boundaries, UpdatePattern updatePattern,
        int steps, double alpha, String pattern, Output output, ColorScheme colorScheme) throws IOException {
    Rule rule = new Rule(ruleNumber);
    Row row = new Row(size, rule, boundaries, updatePattern, pattern, alpha); // e.g. 00010011011111
    Stats stats = new Stats();

    FileOutputStream finalImage = null;
    Graphics2D g = null;
    BufferedImage img = null;//  w  ww  .  ja  v  a2s. c o  m

    if (output != Output.noOutput) {
        String fileName = "rule" + ruleNumber;
        // pattern
        if (pattern != null)
            fileName += pattern;
        // alpha
        if (alpha > 0)
            fileName += String.format("_a%02d", (int) (alpha * 100));
        // updatePattern
        if (updatePattern != UpdatePattern.synchronous)
            fileName += "-" + updatePattern;
        fileName += ".jpeg";

        File file = new File(fileName);
        finalImage = new FileOutputStream(file);

        int width = (int) (cellSize * (size + 1) * (output == Output.all ? 1.25 : 1));
        int height = cellSize * (steps + 1);
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        g = img.createGraphics();
        g.setBackground(Color.white);
        g.clearRect(0, 0, width, height);
        g.setColor(Color.black);
    }

    int startMeansFromStep = 50;
    List<Double> densities = new LinkedList<Double>();
    double totalDensities = 0;

    double prevValue = 0;
    double prevDelta = 0;
    double prevOnes = 0;
    double prevOnesDelta = 0;

    for (int t = 0; t < steps; t++) {
        if (t >= startMeansFromStep) {
            double density = row.getDensity();
            densities.add(density);
            totalDensities += density;
        }
        // System.out.println(String.format("%4d", t) + " " + row.toString() + " ones=" + row.getOnes());
        if (output != Output.noOutput) {
            for (int j = 0; j < row.getSize(); j++) {

                switch (colorScheme) {
                case noColor:
                    if (row.getCell(j).getState()) {
                        g.setColor(Color.black);
                        g.fillRect(j * cellSize, t * cellSize, cellSize, cellSize);
                    }
                    break;
                case omegaColor:
                    g.setColor(row.getCell(j).getOmegaColor());
                    g.fillRect(j * cellSize, t * cellSize, cellSize, cellSize);
                    break;
                case activationColor:
                    if (row.getCell(j).getState()) {
                        g.setColor(row.getCell(j).getColor());
                        g.fillRect(j * cellSize, t * cellSize, cellSize, cellSize);
                    }
                    break;
                }
            }

            if (output == Output.all) {
                double value = row.getValue();
                double delta = Math.abs(value - prevValue);
                double ones = row.getOnes();
                double onesDelta = Math.abs(ones - prevOnes);
                if (t > 0) {
                    g.setColor(Color.red);
                    g.drawLine((int) (prevValue * cellSize / 4.0) + cellSize * (size + 1),
                            (int) ((t - 1) * cellSize), (int) (value * cellSize / 4.0) + cellSize * (size + 1),
                            (int) (t * cellSize));
                    g.setColor(Color.blue);
                    g.drawLine((int) (prevOnes * cellSize / 4.0) + cellSize * (size + 1),
                            (int) ((t - 1) * cellSize), (int) (ones * cellSize / 4.0) + cellSize * (size + 1),
                            (int) (t * cellSize));
                    if (t > 1) {
                        g.setColor(Color.orange);
                        g.drawLine((int) (prevDelta * cellSize / 4.0) + cellSize * (size + 1),
                                (int) ((t - 1) * cellSize),
                                (int) (delta * cellSize / 4.0) + cellSize * (size + 1), (int) (t * cellSize));
                        g.setColor(Color.cyan);
                        g.drawLine((int) (prevOnesDelta * cellSize / 4.0) + cellSize * (size + 1),
                                (int) ((t - 1) * cellSize),
                                (int) (onesDelta * cellSize / 4.0) + cellSize * (size + 1),
                                (int) (t * cellSize));
                    }
                }
                prevValue = value;
                prevDelta = delta;
                prevOnes = ones;
                prevOnesDelta = onesDelta;
            }
        }

        row = new Row(row);
    }

    double means = totalDensities / densities.size();
    double var = 0;
    for (double density : densities)
        var += Math.pow(density - means, 2);
    var = var / densities.size();
    System.out.println("Rule: " + ruleNumber + " Boundaties: " + boundaries + " UpdatePattern: " + updatePattern
            + " Alpha: " + String.format("%.3f", alpha) + " Means: " + String.format("%.6f", means)
            + " Variance: " + String.format("%.6f", var));
    stats.setMeans(means);
    stats.setVariance(var);

    if (output != Output.noOutput) {
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(finalImage);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img);
        param.setQuality(1.0f, true);
        encoder.encode(img, param);
        finalImage.flush();
        finalImage.close();
    }

    return stats;
}

From source file:net.sf.mzmine.modules.visualization.scatterplot.scatterplotchart.ScatterPlotRenderer.java

/**
 * Draws an item label./*from w  ww .j av a2 s .  c  o m*/
 * 
 * @param g2
 *            the graphics device.
 * @param orientation
 *            the orientation.
 * @param dataset
 *            the dataset.
 * @param series
 *            the series index (zero-based).
 * @param item
 *            the item index (zero-based).
 * @param x
 *            the x coordinate (in Java2D space).
 * @param y
 *            the y coordinate (in Java2D space).
 * @param negative
 *            indicates a negative value (which affects the item label
 *            position).
 */
protected void drawItemLabel(Graphics2D g2, PlotOrientation orientation, XYDataset dataset, int series,
        int item, double x, double y, boolean negative) {

    XYItemLabelGenerator generator = getItemLabelGenerator(series, item);
    Font labelFont = getItemLabelFont(series, item);
    g2.setFont(labelFont);
    String label = generator.generateLabel(dataset, series, item);

    if ((label == null) || (label.length() == 0))
        return;

    // get the label position..
    ItemLabelPosition position = null;
    if (!negative) {
        position = getPositiveItemLabelPosition(series, item);
    } else {
        position = getNegativeItemLabelPosition(series, item);
    }

    // work out the label anchor point...
    Point2D anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), x, y, orientation);

    FontMetrics metrics = g2.getFontMetrics(labelFont);
    int width = SwingUtilities.computeStringWidth(metrics, label) + 2;
    int height = metrics.getHeight();

    int X = (int) (anchorPoint.getX() - (width / 2));
    int Y = (int) (anchorPoint.getY() - (height));

    g2.setPaint(searchColor);
    g2.fillRect(X, Y, width, height);

    super.drawItemLabel(g2, orientation, dataset, series, item, x, y, negative);

}

From source file:org.kalypso.ogc.gml.map.MapPanel.java

/**
 * If a message is present, paint it and return true
 */// ww  w .ja  va2  s. c o m
private void paintStatus(final Graphics2D g) {
    if (m_status.isOK())
        return;

    final String message = m_status.getMessage();

    final int stringWidth = g.getFontMetrics().stringWidth(message);

    final int width = getWidth();
    final int height = getHeight();

    g.setColor(m_backgroundColor);
    g.fillRect(0, 0, width, height);
    g.setColor(Color.black);

    g.drawString(message, (width - stringWidth) / 2, height / 2);
}

From source file:savant.view.tracks.BAMTrackRenderer.java

/**
 * Draw the legend for bases, but also the entries for insertions and
 * deletions.//from w  ww. j ava 2 s.c om
 */
private void drawBaseLegendExtended(Graphics2D g2, int x, int y, ColourKey... keys) {
    drawBaseLegend(g2, x, y, keys);

    y += LEGEND_LINE_HEIGHT;
    g2.setColor(Color.BLACK);
    g2.fillRect(x, y - SWATCH_SIZE.height + 2, SWATCH_SIZE.width, SWATCH_SIZE.height);
    g2.setColor(Color.BLACK);
    g2.drawString("Deletion", x + SWATCH_SIZE.width + 3, y);
    x += 66;
    Shape s = drawInsertion(g2, x, y - SWATCH_SIZE.height + 2, 12.0, SWATCH_SIZE.height);
    g2.setColor(Color.BLACK);
    g2.setStroke(new BasicStroke(0.25f));
    g2.draw(s);
    g2.drawString("Insertion", x + 12, y);
}

From source file:ste.travian.world.TileRenderer.java

/**
 * Draws the visual representation of a single data item.
 *
 * @param g2  the graphics device./*  w  w  w .j  a  v a 2  s. co  m*/
 * @param state  the renderer state.
 * @param dataArea  the area within which the data is being drawn.
 * @param info  collects information about the drawing.
 * @param plot  the plot (can be used to obtain standard color 
 *              information etc).
 * @param domainAxis  the domain (horizontal) axis.
 * @param rangeAxis  the range (vertical) axis.
 * @param dataset  the dataset.
 * @param series  the series index (zero-based).
 * @param item  the item index (zero-based).
 * @param crosshairState  crosshair information for the plot 
 *                        (<code>null</code> permitted).
 * @param pass  the pass index.
 */
public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info,
        XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item,
        CrosshairState crosshairState, int pass) {

    // get the data point...
    double x = dataset.getXValue(series, item);
    double y = dataset.getYValue(series, item);
    double adjx = (this.dotWidth - 1) / 2.0;
    double adjy = (this.dotHeight - 1) / 2.0;
    if (Double.isNaN(y)) {
        return;
    }

    PlotOrientation orientation = plot.getOrientation();
    RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
    RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
    double transX = domainAxis.valueToJava2D(x, dataArea, xAxisLocation) - adjx;
    double transY = rangeAxis.valueToJava2D(y, dataArea, yAxisLocation) - adjy;

    g2.setPaint(getItemPaint(series, item));
    if (orientation == PlotOrientation.HORIZONTAL) {
        g2.fillRect((int) transY, (int) transX, this.dotHeight, this.dotWidth);
    } else if (orientation == PlotOrientation.VERTICAL) {
        g2.fillRect((int) transX, (int) transY, this.dotWidth, this.dotHeight);
    }

    int domainAxisIndex = plot.getDomainAxisIndex(domainAxis);
    int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis);
    updateCrosshairValues(crosshairState, x, y, domainAxisIndex, rangeAxisIndex, transX, transY, orientation);

    // add an entity for the item, but only if it falls within the data
    // area...
    EntityCollection entities = null;
    if (info != null) {
        entities = info.getOwner().getEntityCollection();
    }
    int xx = (int) transX;
    int yy = (int) transY;
    if (orientation == PlotOrientation.HORIZONTAL) {
        xx = (int) transY;
        yy = (int) transX;
    }
    if (entities != null && dataArea.contains(xx, yy)) {
        addEntity(entities, null, dataset, series, item, (int) xx, (int) yy);
    }

}

From source file:com.joliciel.jochre.graphics.RowOfShapesImpl.java

public BufferedImage getImage() {
    if (this.image == null && this.container != null) {
        int buffer = 5;
        int width = this.container.getOriginalImage().getWidth();
        int height = this.getBottom() - this.getTop() + 1 + (buffer * 2);
        int bottom = (this.getTop() - buffer) + height;

        if (bottom > this.container.getOriginalImage().getHeight()) {
            int overlap = bottom - this.container.getOriginalImage().getHeight();
            height = height - overlap;/*from   ww  w  .ja v a2s.co  m*/
        }
        BufferedImage rowImage = this.container.getOriginalImage().getSubimage(0, this.getTop() - buffer, width,
                height);

        double scale = (double) ROW_IMAGE_WIDTH / (double) width;
        int newHeight = (int) Math.floor(scale * height);
        if (this.container.getOriginalImage().getColorModel() instanceof IndexColorModel) {
            image = new BufferedImage(ROW_IMAGE_WIDTH, newHeight, this.container.getOriginalImage().getType(),
                    (IndexColorModel) this.container.getOriginalImage().getColorModel());
        } else {
            image = new BufferedImage(ROW_IMAGE_WIDTH, newHeight, this.container.getOriginalImage().getType());
        }
        Graphics2D graphics2d = image.createGraphics();

        AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
        graphics2d.drawRenderedImage(rowImage, at);

        // white out the space to the right & left of this row
        graphics2d.setColor(Color.WHITE);
        graphics2d.fillRect(0, 0, (int) Math.round((this.getLeft() - 5) * scale),
                (int) Math.round(height * scale));
        graphics2d.fillRect((int) Math.round((this.getRight() + 5) * scale), 0,
                (int) Math.round((width - this.getRight()) * scale), (int) Math.round(height * scale));

    }
    return image;
}