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

@Override
public void paint(Graphics g, JComponent c) {
    Graphics2D g2 = (Graphics2D) g.create();

    // Paint the view.
    super.paint(g2, c);

    if (mActive) {
        // Create a radial gradient, transparent in the middle.
        java.awt.geom.Point2D center = new java.awt.geom.Point2D.Float(mX, mY);
        float radius = 72;
        float[] dist = { 0.0f, 1.0f };
        Color[] colors = { new Color(0.0f, 0.0f, 0.0f, 0.0f), Color.BLACK };
        RadialGradientPaint p = new RadialGradientPaint(center, radius, dist, colors);
        g2.setPaint(p);//from   ww w  .  ja  v  a 2 s .co m
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .6f));
        g2.fillRect(0, 0, c.getWidth(), c.getHeight());
    }

    g2.dispose();
}

From source file:org.n52.oxf.render.sos.ScatterPlotChartRenderer.java

@Override
public void render(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, CrosshairState crosshairState) {
    float[][] data = getData();

    g2.setPaint(Color.red);/*from ww  w .  ja  v  a2 s  .c  o m*/

    if (super.getData() != null) {
        for (int i = 0; i < data[0].length; i++) {
            float x = data[0][i];
            float y = data[1][i];

            int transX = (int) getDomainAxis().valueToJava2D(x, dataArea, RectangleEdge.BOTTOM);
            int transY = (int) getRangeAxis().valueToJava2D(y, dataArea, RectangleEdge.LEFT);
            g2.fillRect(transX, transY, dotSize, dotSize);
        }
    }
}

From source file:dcstore.web.ImagesWeb.java

private void resizeImage(String inPath, int w, int h, String outPath) {
    try {/*from   w  w  w .j ava2s.c o  m*/
        BufferedImage originalImage = ImageIO.read(new File(inPath));
        int ow, oh;
        ow = originalImage.getWidth();
        oh = originalImage.getHeight();
        double ratio = (double) ow / (double) oh;
        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
        int ch = (int) Math.round(w / ratio);

        BufferedImage resizedImage = new BufferedImage(w, h, type);
        Graphics2D g = resizedImage.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(Color.white);
        g.fillRect(0, 0, w, h);
        g.drawImage(originalImage, 0, (int) (((float) h - (float) ch) / 2), w, ch, null);
        g.dispose();
        ImageIO.write(resizedImage, "jpg", new File(outPath));
    } catch (Exception e) {
        FacesContext.getCurrentInstance().addMessage("",
                new FacesMessage("Error while resizeing image: " + e.getMessage()));
    }
}

From source file:org.limy.eclipse.qalab.outline.sequence.SequenceImageCreator.java

/**
 * V?[PX?}?? layoutData, pngFile ?o?B// ww w  . j  a v a 2 s  .c o  m
 * @param root V?[PX?}Bean
 * @throws IOException I/OO
 * @throws ParserException 
 */
private void writeSequence(SequenceBean root) throws IOException, ParserException {
    StringWriter out = new StringWriter();
    Context context = new VelocityContext();
    context.put("root", root);
    VelocitySupport.write(new File(LimyQalabPlugin.getDefault().getPluginRoot(), "resource/sequence/index.vm")
            .getAbsolutePath(), context, out);
    File txtFile = LimyQalabUtils.createTempFile(env.getProject(), "sequence.txt");
    pngFile = LimyQalabUtils.createTempFile(env.getProject(), "sequence.png");
    FileUtils.writeByteArrayToFile(txtFile, out.toString().getBytes());

    Parser parser = ParserFactory.getInstance().getDefaultParser();
    NodeFactory nodeFactory = ParserFactory.getInstance().getNodeFactoryForParser(parser);
    Diagram diagram = new Diagram(parser, nodeFactory);

    PushbackReader reader = new PushbackReader(new FileReader(txtFile));
    try {
        diagram.parse(reader);
    } finally {
        reader.close();
    }

    Model model = new Model(new ExceptionHandler() {
        public void exception(Exception e) {
            e.printStackTrace();
        }
    }, diagram);

    BufferedImage bi = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = bi.createGraphics();
    layoutData = new LayoutData(new SwingStringMeasure(graphics));
    diagram.layout(layoutData);

    int height = layoutData.getHeight();
    int width = layoutData.getWidth();

    BufferedImage png = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D pngGraphics = png.createGraphics();
    pngGraphics.setClip(0, 0, width, height);
    Map<Key, Object> hintsMap = new HashMap<Key, Object>();
    hintsMap.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    pngGraphics.addRenderingHints(hintsMap);
    pngGraphics.setBackground(Prefs.getColorValue(Prefs.BACKGROUND_COLOR));
    pngGraphics.fillRect(0, 0, width, height);

    SwingPainter painter = new SwingPainter();
    painter.setGraphics(pngGraphics);
    model.layout(layoutData);
    layoutData.paint(painter);

    ImageIO.write(png, "png", pngFile);
}

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

private void renderPopup(HashMap<String, Object> pPopupInfo, Graphics2D pG2D) {
    Point location = (Point) pPopupInfo.get("popup.location");
    String label = (String) pPopupInfo.get("popup.label");
    if (location == null || label == null) {
        return;/*from www. java  2s.c om*/
    }
    pG2D.setColor(new Color(255, 255, 204));
    Rectangle2D labelBounds = pG2D.getFontMetrics().getStringBounds(label, pG2D);
    pG2D.fillRect(location.x, location.y - (int) labelBounds.getHeight(), (int) labelBounds.getWidth() + 5,
            (int) labelBounds.getHeight() + 5);
    pG2D.setColor(Color.BLACK);
    pG2D.drawRect(location.x, location.y - (int) labelBounds.getHeight(), (int) labelBounds.getWidth() + 5,
            (int) labelBounds.getHeight() + 5);
    pG2D.drawString(label, location.x + 2, location.y);

}

From source file:org.objectweb.proactive.extensions.timitspmd.util.charts.MatrixChart.java

private void buildFinalChart(String title, String subTitle, String filename, String xAxisLabel,
        String yAxisLabel, int width, int height) {
    this.buildMainChart(title, subTitle, xAxisLabel, yAxisLabel, filename);

    this.buildLegendChart(5);

    BufferedImage mainChartImage = this.mainChart.createBufferedImage(width, height);
    BufferedImage legendChartImage = this.legendChart.createBufferedImage(width / 6, height / 3);
    BufferedImage info = null;//  w  w  w  .  j a va  2s.  com
    try {
        info = ImageIO.read(MatrixChart.logoFile);
    } catch (IOException ex) {
    }

    BufferedImage total = new BufferedImage(width + (width / 6), height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = total.createGraphics();

    g.drawImage(mainChartImage, 0, 0, null);
    g.drawImage(legendChartImage, width, height / 4, null);
    g.setPaint(Color.WHITE);
    g.fillRect(width, 0, width, height / 4);
    g.fillRect(width, (height / 4) + (height / 3), width, height);
    if (info != null) {
        // g.drawImage(info, (width+(width/6))-info.getWidth(),10, null); //
        // up-right
        g.drawImage(info, (width + (width / 6)) - info.getWidth(), height - info.getHeight(), null); // down-right
    }
    g.dispose();

    try {
        javax.imageio.ImageIO.write(total, "png", XMLHelper.createFileWithDirs(filename));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:org.opencms.pdftools.CmsPdfThumbnailGenerator.java

/**
 * Generates the image data for a thumbnail from a PDF.<p>
 *
 * The given width and height determine the box in which the thumbnail should fit.
 * The resulting image will always have these dimensions, even if the aspect ratio of the actual PDF
 * page is different from the ratio of the given width and height. In this case, the size of the rendered
 * page will be reduced, and the rest of the image will be filled with blank space.<p>
 *
 * If one of width or height is negative, then that dimension is chosen so the resulting aspect ratio is the
 * aspect ratio of the PDF page.// www . j  a  v a  2 s .  com
 *
 * @param pdfInputStream the input stream for reading the PDF data
 * @param boxWidth the width of the box in which the thumbnail should fit
 * @param boxHeight the height of the box in which the thumbnail should fit
 * @param imageFormat the image format (png, jpg, gif)
 * @param pageIndex the index of the page for which to render the thumbnail (starting at 0)
 *
 * @return the image data for the thumbnail, in the given image format
 * @throws Exception if something goes wrong
 */
public byte[] generateThumbnail(InputStream pdfInputStream, int boxWidth, int boxHeight, String imageFormat,
        int pageIndex) throws Exception {

    org.jpedal.io.ObjectStore.temp_dir = CmsFileUtil.normalizePath(OpenCms.getSystemInfo().getWebInfRfsPath()
            + CmsPdfThumbnailCache.PDF_CACHE_FOLDER + File.separatorChar);
    PdfDecoder decoder = new PdfDecoder(true);

    try {
        decoder.openPdfFileFromInputStream(pdfInputStream, false);
        int numPages = decoder.getPageCount();
        if (pageIndex >= numPages) {
            pageIndex = numPages - 1;
        } else if (pageIndex < 0) {
            pageIndex = 0;
        }

        // width/height are in points (1/72 of an inch)
        PdfPageData pageData = decoder.getPdfPageData();
        double aspectRatio = (pageData.getCropBoxWidth(1 + pageIndex) * 1.0)
                / pageData.getCropBoxHeight(1 + pageIndex);
        int rotation = pageData.getRotation(1 + pageIndex);
        if ((rotation == 90) || (rotation == 270)) {
            // landscape
            aspectRatio = 1 / aspectRatio;
        }

        if ((boxWidth < 0) && (boxHeight < 0)) {
            throw new IllegalArgumentException("At least one of width / height must be positive!");
        } else if ((boxWidth < 0) && (boxHeight > 0)) {
            boxWidth = (int) Math.round(aspectRatio * boxHeight);
        } else if ((boxWidth > 0) && (boxHeight < 0)) {
            boxHeight = (int) Math.round(boxWidth / aspectRatio);
        }

        // calculateDimensions only takes integers, but only their ratio matters, we multiply the box width with a big number
        int fakePixelWidth = (int) (FAKE_PIXEL_MULTIPLIER * aspectRatio);
        int fakePixelHeight = (FAKE_PIXEL_MULTIPLIER);
        int[] unpaddedThumbnailDimensions = CmsImageScaler.calculateDimension(fakePixelWidth, fakePixelHeight,
                boxWidth, boxHeight);
        decoder.decodePage(1 + pageIndex);
        BufferedImage pageImage = decoder.getPageAsImage(1 + pageIndex);
        BufferedImage paddedImage = new BufferedImage(boxWidth, boxHeight, BufferedImage.TYPE_3BYTE_BGR);

        Graphics2D g = paddedImage.createGraphics();
        int uw = unpaddedThumbnailDimensions[0];
        int uh = unpaddedThumbnailDimensions[1];

        // Scale to fit in  the box
        AffineTransformOp op = new AffineTransformOp(AffineTransform
                .getScaleInstance((uw * 1.0) / pageImage.getWidth(), (uh * 1.0) / pageImage.getHeight()),
                AffineTransformOp.TYPE_BILINEAR);

        g.setColor(Color.WHITE);
        // Fill box image with white, then draw the image data for the PDF in the middle
        g.fillRect(0, 0, paddedImage.getWidth(), paddedImage.getHeight());
        //g.drawImage(pageImage, (boxWidth - pageImage.getWidth()) / 2, (boxHeight - pageImage.getHeight()) / 2, null);
        g.drawImage(pageImage, op, (boxWidth - uw) / 2, (boxHeight - uh) / 2);
        BufferedImage pageThumbnail = paddedImage;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIOUtil.writeImage(pageThumbnail, imageFormat, out);
        byte[] imageData = out.toByteArray();
        return imageData;
    } finally {
        if (decoder.isOpen()) {
            decoder.closePdfFile();
        }
        pdfInputStream.close();

    }
}

From source file:components.SizeDisplayer.java

protected void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g.create(); //copy g
    Dimension minSize = getMinimumSize();
    Dimension prefSize = getPreferredSize();
    Dimension size = getSize();/*from   ww w  .  j a  v  a2 s  .  c  om*/
    int prefX = 0, prefY = 0;

    //Set hints so text looks nice.
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    //Draw the maximum size rectangle if we're opaque.
    if (isOpaque()) {
        g2d.setColor(getBackground());
        g2d.fillRect(0, 0, size.width, size.height);
    }

    //Draw the icon.
    if (icon != null) {
        Composite oldComposite = g2d.getComposite();
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f));
        icon.paintIcon(this, g2d, (size.width - icon.getIconWidth()) / 2,
                (size.height - icon.getIconHeight()) / 2);
        g2d.setComposite(oldComposite);
    }

    //Draw the preferred size rectangle.
    prefX = (size.width - prefSize.width) / 2;
    prefY = (size.height - prefSize.height) / 2;
    g2d.setColor(Color.RED);
    g2d.drawRect(prefX, prefY, prefSize.width - 1, prefSize.height - 1);

    //Draw the minimum size rectangle.
    if (minSize.width != prefSize.width || minSize.height != prefSize.height) {
        int minX = (size.width - minSize.width) / 2;
        int minY = (size.height - minSize.height) / 2;
        g2d.setColor(Color.CYAN);
        g2d.drawRect(minX, minY, minSize.width - 1, minSize.height - 1);
    }

    //Draw the text.
    if (text != null) {
        Dimension textSize = getTextSize(g2d);
        g2d.setColor(getForeground());
        g2d.drawString(text, (size.width - textSize.width) / 2,
                (size.height - textSize.height) / 2 + g2d.getFontMetrics().getAscent());
    }
    g2d.dispose();
}

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

private void writeImage2HTML(HTMLReportArchive report, LaneCoordinates laneCoordinates,
        TileNumeration tileNumeration) throws IOException {
    final MappingQualityTableModel model = new MappingQualityTableModel(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  w w w  .  j a  v a2s. co  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 = 50; // 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;

        for (int c = 0; c < model.getColumnCount(); c++) {
            TileCoordinates tileCoordinate = model.getCoordinateAt(r, c);
            MappingQualityMatrix matrix = getMeanQualityMatrix(tileCoordinate);

            if (matrix != null) {
                if (r < MappingQualityMatrix.THRESHOLDS.length) {
                    ColorPaintScale paintScale = MappingQualityCellRenderer.getThresholdPaintScale();
                    BufferedImage image = (BufferedImage) matrix
                            .createBufferedImageForThreshold(MappingQualityMatrix.THRESHOLDS[r], paintScale);
                    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 {
                    ColorPaintScale paintScale = MappingQualityCellRenderer.getAveragePaintScale();
                    BufferedImage image = (BufferedImage) matrix.createBufferedImage(paintScale);
                    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: " + tileCoordinate + "\n");
            }
            if (c == model.getTopBottomSeparatorColumn()) {
                separator = topBottomSeparator;
            }
        }
    }

    g2.dispose();
    String imgFileName = "quality_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");

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

From source file:org.eurocarbdb.application.glycoworkbench.plugin.reporting.ProfilesComparisonReportChartCanvas.java

protected void paintComponent(Graphics g) {

    // prepare graphic object
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // set clipping area
    if (is_printing) {
        g2d.translate(-draw_area.x, -draw_area.y);
        g2d.setClip(draw_area);/*from   ww w.j av a 2 s. c  om*/
    }

    //paint canvas background
    if (!is_printing) {
        g2d.setColor(getBackground());
        g2d.fillRect(0, 0, getWidth(), getHeight());
    }

    // paint white background on drawing area    
    g2d.setColor(Color.white);
    g2d.fillRect(draw_area.x, draw_area.y, draw_area.width, draw_area.height);
    if (!is_printing) {
        g2d.setColor(Color.black);
        g2d.draw(draw_area);
    }

    // paint
    paintChart(g2d);

    // dispose graphic object
    g2d.dispose();

    revalidate();
}