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:com.joliciel.jochre.search.highlight.ImageSnippet.java

public BufferedImage getImage() {
    try {// w  w  w  . j  a v a2  s  .  c  o  m
        BufferedImage originalImage = ImageIO.read(imageFile);
        BufferedImage imageSnippet = new BufferedImage(this.rectangle.getWidth(), this.rectangle.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        originalImage = originalImage.getSubimage(this.rectangle.getLeft(), this.rectangle.getTop(),
                this.rectangle.getWidth(), this.rectangle.getHeight());
        Graphics2D graphics2D = imageSnippet.createGraphics();
        graphics2D.drawImage(originalImage, 0, 0, this.rectangle.getWidth(), this.rectangle.getHeight(), null);
        int extra = 2;
        for (Rectangle rect : this.highlights) {
            graphics2D.setStroke(new BasicStroke(1));
            graphics2D.setPaint(Color.BLACK);
            graphics2D.drawRect(rect.getLeft() - this.rectangle.getLeft() - extra,
                    rect.getTop() - this.rectangle.getTop() - extra, rect.getWidth() + (extra * 2),
                    rect.getHeight() + (extra * 2));
            graphics2D.setColor(new Color(255, 255, 0, 127));
            graphics2D.fillRect(rect.getLeft() - this.rectangle.getLeft() - extra,
                    rect.getTop() - this.rectangle.getTop() - extra, rect.getWidth() + (extra * 2),
                    rect.getHeight() + (extra * 2));
        }
        return imageSnippet;
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:org.wkm.mtool.service.QRCodeService.java

/**
 * ??(QRCode)//  w  ww.  j a va 2  s .c  o m
 * @param content
 * @param imgFile
 */
private void encoderQRCode(String content, File imgFile) {
    try {
        Qrcode qrcodeHandler = new Qrcode();
        qrcodeHandler.setQrcodeErrorCorrect('M');
        qrcodeHandler.setQrcodeEncodeMode('B');
        qrcodeHandler.setQrcodeVersion(7);

        System.out.println(content);
        byte[] contentBytes = content.getBytes(Consts.UTF_8.name());

        BufferedImage bufImg = new BufferedImage(140, 140, BufferedImage.TYPE_INT_RGB);

        Graphics2D gs = bufImg.createGraphics();

        gs.setBackground(Color.WHITE);
        gs.clearRect(0, 0, 140, 140);

        // ? > BLACK
        gs.setColor(Color.BLACK);

        // ??? ???
        int pixoff = 2;
        //  > ?
        if (contentBytes.length > 0 && contentBytes.length < 120) {
            boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
            for (int i = 0; i < codeOut.length; i++) {
                for (int j = 0; j < codeOut.length; j++) {
                    if (codeOut[j][i]) {
                        gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                    }
                }
            }
        } else {
            System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. ");
        }

        gs.dispose();
        bufImg.flush();

        // ??QRCode
        ImageIO.write(bufImg, "png", imgFile);

    } catch (Exception e) {
        log.info("Exception:" + e.getMessage());
    }
}

From source file:TransferableScribblePane.java

/** We override this method to draw ourselves. */
public void paintComponent(Graphics g) {
    // Let the superclass do its painting first
    super.paintComponent(g);

    // Make a copy of the Graphics context so we can modify it
    Graphics2D g2 = (Graphics2D) (g.create());

    // Our superclass doesn't paint the background, so do this ourselves.
    g2.setColor(getBackground());//  w ww  .j  ava2 s . c  om
    g2.fillRect(0, 0, getWidth(), getHeight());

    // Set the line width and color to use for the foreground
    g2.setStroke(stroke);
    g2.setColor(this.getForeground());

    // Now loop through the PolyLine shapes and draw them all
    int numlines = lines.size();
    for (int i = 0; i < numlines; i++) {
        PolyLine line = (PolyLine) lines.get(i);
        if (line == selectedLine) { // If it is the selected line
            g2.setStroke(selectedStroke); // Set dash pattern
            g2.draw(line); // Draw the line
            g2.setStroke(stroke); // Revert to solid lines
        } else
            g2.draw(line); // Otherwise just draw the line
    }
}

From source file:edu.ku.brc.specify.tools.FormDisplayer.java

/**
 * Generates an Image for the View./* w w w  .  j a v  a2  s.  c o  m*/
 */
protected void generateViewImage(final ViewIFace view) {
    Rectangle rect = frame.getContentPane().getBounds();
    if (rect.width == 0 || rect.height == 0) {
        return;
    }

    BufferedImage bufImage = new BufferedImage(rect.width, rect.height,
            (doPNG ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB));
    Graphics2D g2 = bufImage.createGraphics();
    if (!doPNG) {
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, rect.width, rect.height);
    }
    g2.setRenderingHints(ERDVisualizer.createTextRenderingHints());
    frame.getContentPane().paint(g2);

    g2.dispose();

    String baseFileName = outputDir.getAbsoluteFile() + "/" + view.getName() + "_" + viewInx; //$NON-NLS-1$ //$NON-NLS-2$
    File imgFile = new File(baseFileName + (doPNG ? ".png" : ".jpg")); //$NON-NLS-1$ //$NON-NLS-2$
    System.out.println(imgFile.getAbsolutePath());
    try {
        ImageIO.write(bufImage, "PNG", imgFile); //$NON-NLS-1$

        entries.add(new Pair<String, File>(view.getName(), imgFile));

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormDisplayer.class, ex);
        ex.printStackTrace();
    }
}

From source file:FontShow.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    Font font = new Font("Dialog", Font.PLAIN, 96);
    g2.setFont(font);/*from  w w  w  .  j a v a  2 s . c o  m*/
    int width = getSize().width;
    int height = getSize().height;

    String message = "Java2s";

    FontRenderContext frc = g2.getFontRenderContext();
    LineMetrics metrics = font.getLineMetrics(message, frc);
    float messageWidth = (float) font.getStringBounds(message, frc).getWidth();

    // center text
    float ascent = metrics.getAscent();
    float descent = metrics.getDescent();
    float x = (width - messageWidth) / 2;
    float y = (height + metrics.getHeight()) / 2 - descent;

    int PAD = 25;
    g2.setPaint(getBackground());
    g2.fillRect(0, 0, width, height);

    g2.setPaint(getForeground());
    g2.drawString(message, x, y);

    g2.setPaint(Color.white); // Base lines
    drawLine(g2, x - PAD, y, x + messageWidth + PAD, y);
    drawLine(g2, x, y + PAD, x, y - ascent - PAD);
    g2.setPaint(Color.green); // Ascent line
    drawLine(g2, x - PAD, y - ascent, x + messageWidth + PAD, y - ascent);
    g2.setPaint(Color.red); // Descent line
    drawLine(g2, x - PAD, y + descent, x + messageWidth + PAD, y + descent);
}

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

private void plot(final Graphics2D g2, final Rectangle2D dataArea, final double[] v, final boolean big) {

    int x, y;/*from   w  w w  .ja  v a 2 s.c o m*/
    x = (int) plot.getDomainAxis().valueToJava2D(v[0], dataArea, RectangleEdge.BOTTOM);

    y = (int) plot.getRangeAxis().valueToJava2D(v[1], dataArea, RectangleEdge.LEFT);

    if (big) {
        g2.fillRect(x - 1, y - 1, 3, 3);
    } else {
        g2.fillRect(x, y, 1, 1);
    }
}

From source file:ScribbleDragAndDrop.java

/**
 * This method implements the DragGestureListener interface. It will be
 * invoked when the DragGestureRecognizer thinks that the user has initiated
 * a drag. If we're not in drawing mode, then this method will try to figure
 * out which Scribble object is being dragged, and will initiate a drag on
 * that object.//  w w  w.j  ava  2 s  .  co  m
 */
public void dragGestureRecognized(DragGestureEvent e) {
    // Don't drag if we're not in drag mode
    if (!dragMode)
        return;

    // Figure out where the drag started
    MouseEvent inputEvent = (MouseEvent) e.getTriggerEvent();
    int x = inputEvent.getX();
    int y = inputEvent.getY();

    // Figure out which scribble was clicked on, if any by creating a
    // small rectangle around the point and testing for intersection.
    Rectangle r = new Rectangle(x - LINEWIDTH, y - LINEWIDTH, LINEWIDTH * 2, LINEWIDTH * 2);
    int numScribbles = scribbles.size();
    for (int i = 0; i < numScribbles; i++) { // Loop through the scribbles
        Scribble s = (Scribble) scribbles.get(i);
        if (s.intersects(r)) {
            // The user started the drag on top of this scribble, so
            // start to drag it.

            // First, remember which scribble is being dragged, so we can
            // delete it later (if this is a move rather than a copy)
            beingDragged = s;

            // Next, create a copy that will be the one dragged
            Scribble dragScribble = (Scribble) s.clone();
            // Adjust the origin to the point the user clicked on.
            dragScribble.translate(-x, -y);

            // Choose a cursor based on the type of drag the user initiated
            Cursor cursor;
            switch (e.getDragAction()) {
            case DnDConstants.ACTION_COPY:
                cursor = DragSource.DefaultCopyDrop;
                break;
            case DnDConstants.ACTION_MOVE:
                cursor = DragSource.DefaultMoveDrop;
                break;
            default:
                return; // We only support move and copys
            }

            // Some systems allow us to drag an image along with the
            // cursor. If so, create an image of the scribble to drag
            if (dragSource.isDragImageSupported()) {
                Rectangle scribbleBox = dragScribble.getBounds();
                Image dragImage = this.createImage(scribbleBox.width, scribbleBox.height);
                Graphics2D g = (Graphics2D) dragImage.getGraphics();
                g.setColor(new Color(0, 0, 0, 0)); // transparent background
                g.fillRect(0, 0, scribbleBox.width, scribbleBox.height);
                g.setColor(Color.black);
                g.setStroke(linestyle);
                g.translate(-scribbleBox.x, -scribbleBox.y);
                g.draw(dragScribble);
                Point hotspot = new Point(-scribbleBox.x, -scribbleBox.y);

                // Now start dragging, using the image.
                e.startDrag(cursor, dragImage, hotspot, dragScribble, this);
            } else {
                // Or start the drag without an image
                e.startDrag(cursor, dragScribble, this);
            }
            // After we've started dragging one scribble, stop looking
            return;
        }
    }
}

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

private void renderDayMarkers(long pStart, long pEnd, Graphics2D pG2D) {
    Date d = new Date(pStart);
    d = DateUtils.setHours(d, 0);//from   w w w . j  ava 2  s.  c om
    d = DateUtils.setMinutes(d, 0);
    d = DateUtils.setSeconds(d, 0);
    d = DateUtils.setMilliseconds(d, 0);

    for (long mark = d.getTime(); mark <= pEnd; mark += DateUtils.MILLIS_PER_HOUR) {
        int markerPos = Math.round((mark - pStart) / DateUtils.MILLIS_PER_MINUTE);
        pG2D.setColor(Color.YELLOW);
        pG2D.fillRect(markerPos, 20, 2, 10);
        pG2D.setColor(Color.WHITE);
        pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 10.0f));
        pG2D.fillRect(markerPos - 5, 15, 12, 10);
        pG2D.setColor(Color.BLACK);
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(mark));
        NumberFormat f = NumberFormat.getNumberInstance();
        f.setMinimumIntegerDigits(2);
        f.setMaximumFractionDigits(2);
        pG2D.drawString(f.format(cal.get(Calendar.HOUR_OF_DAY)), markerPos - 5, 23);
    }

    long currentDay = d.getTime();
    while (currentDay < pEnd) {
        currentDay += DateUtils.MILLIS_PER_DAY;
        int markerPos = Math.round((currentDay - pStart) / DateUtils.MILLIS_PER_MINUTE);
        pG2D.setColor(new Color(123, 123, 123));
        pG2D.fillRect(markerPos, 15, 3, 30);
        SimpleDateFormat f = new SimpleDateFormat("dd.MM.yy");
        String dayLabel = f.format(currentDay);
        Rectangle2D labelBounds = pG2D.getFontMetrics().getStringBounds(dayLabel, pG2D);
        pG2D.setColor(Color.YELLOW);
        int labelWidth = (int) labelBounds.getWidth() + 5;
        pG2D.fillRect(markerPos - (int) Math.rint(labelWidth / 2), 15, labelWidth, 10);
        pG2D.setColor(Color.BLACK);
        pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 10.0f));
        pG2D.drawString(dayLabel, markerPos - (int) Math.rint(labelWidth / 2) + 2, 23);
    }
}

From source file:pl.edu.icm.visnow.system.main.VisNow.java

private static void renderSplashFrame(float progress, String loadText, String bottomTextUpperLine,
        String bottomTextLowerLine) {
    if (splash == null) {
        return;/* w  w w. ja  v a 2  s.  com*/
    }

    try {
        Graphics2D g = splash.createGraphics();
        if (g == null) {
            return;
        }

        if (!splash.isVisible())
            return;

        Rectangle bounds = splash.getBounds();
        Font f = g.getFont();
        FontMetrics fm = g.getFontMetrics(f);
        java.awt.geom.Rectangle2D rect = fm.getStringBounds(loadText, g);
        int texth = (int) Math.ceil(rect.getHeight());
        g.setComposite(AlphaComposite.Clear);
        //g.setColor(Color.RED);
        g.fillRect(PROGRESS_TEXT_X_POSITION, bounds.height - PROGRESS_TEXT_Y_MARGIN - texth - 5,
                bounds.width - PROGRESS_TEXT_X_POSITION, texth + 10);

        g.setFont(lowerLineFont);
        fm = g.getFontMetrics(g.getFont());
        rect = fm.getStringBounds(bottomTextLowerLine, g);
        int lowerLineTextHeight = (int) Math.ceil(rect.getHeight());
        g.fillRect(BOTTOM_TEXT_X_MARGIN, bounds.height - BOTTOM_TEXT_Y_MARGIN - lowerLineTextHeight - 5,
                bounds.width - BOTTOM_TEXT_X_MARGIN, lowerLineTextHeight + 10);

        g.setFont(f);
        fm = g.getFontMetrics(g.getFont());
        rect = fm.getStringBounds(bottomTextUpperLine, g);
        texth = (int) Math.ceil(rect.getHeight());
        g.fillRect(BOTTOM_TEXT_X_MARGIN, bounds.height - lowerLineTextHeight - BOTTOM_TEXT_Y_MARGIN - texth - 5,
                bounds.width - BOTTOM_TEXT_X_MARGIN, lowerLineTextHeight + 10);

        g.setPaintMode();
        //        g.setColor(Color.BLACK);
        g.setColor(new Color(0, 75, 50));
        g.drawString(loadText, PROGRESS_TEXT_X_POSITION, bounds.height - PROGRESS_TEXT_Y_MARGIN);
        g.drawString(bottomTextUpperLine, BOTTOM_TEXT_X_MARGIN,
                bounds.height - lowerLineTextHeight - BOTTOM_TEXT_Y_MARGIN);
        g.setFont(lowerLineFont);
        g.drawString(bottomTextLowerLine, BOTTOM_TEXT_X_MARGIN, bounds.height - BOTTOM_TEXT_Y_MARGIN);
        g.setFont(f);

        //        g.setColor(Color.BLACK);
        g.setColor(new Color(0, 150, 100));
        g.drawRect(PROGRESS_BAR_X_MARGIN, bounds.height - PROGRESS_BAR_Y_MARGIN,
                bounds.width - PROGRESS_BAR_X_MARGIN, PROGRESS_BAR_HEIGHT);
        int progressWidth = bounds.width - 2 * PROGRESS_BAR_X_MARGIN;
        int done = (int) (progressWidth * progress);
        g.fillRect(PROGRESS_BAR_X_MARGIN, bounds.height - PROGRESS_BAR_Y_MARGIN, PROGRESS_BAR_X_MARGIN + done,
                PROGRESS_BAR_HEIGHT);
        if (progress >= 1.0f) {
            g.fillRect(PROGRESS_BAR_X_MARGIN, bounds.height - PROGRESS_BAR_Y_MARGIN,
                    bounds.width - PROGRESS_BAR_X_MARGIN, PROGRESS_BAR_HEIGHT);
        }

        splash.update();
    } catch (IllegalStateException ex) {
    }
}

From source file:edu.umn.cs.spatialHadoop.operations.Plot.java

public static void drawShape(Graphics2D graphics, Shape s, Rectangle fileMbr, int imageWidth, int imageHeight,
        double scale) {
    if (s instanceof NASAPoint) {
        final int MinValue = 7500;
        final int MaxValue = 16000;
        NASAPoint pt = (NASAPoint) s;/*from   w ww.ja  v a 2  s  . c o m*/
        int x = (int) ((pt.x - fileMbr.x1) * imageWidth / (fileMbr.x2 - fileMbr.x1));
        int y = (int) ((pt.y - fileMbr.y1) * imageHeight / (fileMbr.y2 - fileMbr.y1));
        int value = pt.value;

        if (value < min_value && value > 1000)
            min_value = value;
        if (value > max_value)
            max_value = value;

        if (value > 0 && x >= 0 && x < imageWidth && y >= 0 && y < imageHeight) {
            Color color;
            if (value < MinValue) {
                color = Color.BLACK;
            } else if (value < MaxValue) {
                float ratio = 0.78f - 0.78f * (value - MinValue) / (MaxValue - MinValue);
                color = Color.getHSBColor(ratio, 0.5f, 1.0f);
            } else {
                color = Color.WHITE;
            }
            graphics.setColor(color);
            graphics.fillRect(x, y, 1, 1);
        }
    } else if (s instanceof Point) {
        Point pt = (Point) s;
        int x = (int) ((pt.x - fileMbr.x1) * imageWidth / (fileMbr.x2 - fileMbr.x1));
        int y = (int) ((pt.y - fileMbr.y1) * imageHeight / (fileMbr.y2 - fileMbr.y1));

        if (x >= 0 && x < imageWidth && y >= 0 && y < imageHeight)
            graphics.fillRect(x, y, 1, 1);
    } else if (s instanceof Rectangle) {
        Rectangle r = (Rectangle) s;
        int s_x1 = (int) ((r.x1 - fileMbr.x1) * imageWidth / (fileMbr.x2 - fileMbr.x1));
        int s_y1 = (int) ((r.y1 - fileMbr.y1) * imageHeight / (fileMbr.y2 - fileMbr.y1));
        int s_x2 = (int) (((r.x2) - fileMbr.x1) * imageWidth / (fileMbr.x2 - fileMbr.x1));
        int s_y2 = (int) (((r.y2) - fileMbr.y1) * imageHeight / (fileMbr.y2 - fileMbr.y1));
        graphics.drawRect(s_x1, s_y1, s_x2 - s_x1 + 1, s_y2 - s_y1 + 1);
    } else if (s instanceof OGCShape) {
        OGCShape ogc_shape = (OGCShape) s;
        OGCGeometry geom = ogc_shape.geom;
        Color shape_color = graphics.getColor();
        if (geom instanceof OGCGeometryCollection) {
            OGCGeometryCollection geom_coll = (OGCGeometryCollection) geom;
            for (int i = 0; i < geom_coll.numGeometries(); i++) {
                OGCGeometry sub_geom = geom_coll.geometryN(i);
                // Recursive call to draw each geometry
                drawShape(graphics, new OGCShape(sub_geom), fileMbr, imageWidth, imageHeight, scale);
            }
        } else if (geom.getEsriGeometry() instanceof MultiPath) {
            MultiPath path = (MultiPath) geom.getEsriGeometry();
            double sub_geom_alpha = path.calculateLength2D() * scale;
            int color_alpha = sub_geom_alpha > 1.0 ? 255 : (int) Math.round(sub_geom_alpha * 255);

            if (color_alpha == 0)
                return;

            int[] xpoints = new int[path.getPointCount()];
            int[] ypoints = new int[path.getPointCount()];

            for (int i = 0; i < path.getPointCount(); i++) {
                double px = path.getPoint(i).getX();
                double py = path.getPoint(i).getY();

                // Transform a point in the polygon to image coordinates
                xpoints[i] = (int) Math.round((px - fileMbr.x1) * imageWidth / (fileMbr.x2 - fileMbr.x1));
                ypoints[i] = (int) Math.round((py - fileMbr.y1) * imageHeight / (fileMbr.y2 - fileMbr.y1));
            }

            // Draw the polygon
            graphics.setColor(new Color((shape_color.getRGB() & 0x00FFFFFF) | (color_alpha << 24), true));
            if (path instanceof Polygon)
                graphics.drawPolygon(xpoints, ypoints, path.getPointCount());
            else if (path instanceof Polyline)
                graphics.drawPolyline(xpoints, ypoints, path.getPointCount());
        }
    } else if (s instanceof JTSShape) {
        JTSShape jts_shape = (JTSShape) s;
        Geometry geom = jts_shape.geom;
        Color shape_color = graphics.getColor();

        drawJTSShape(graphics, geom, fileMbr, imageWidth, imageHeight, scale, shape_color);
    } else {
        LOG.warn("Cannot draw a shape of type: " + s.getClass());
        Rectangle r = s.getMBR();
        int s_x1 = (int) ((r.x1 - fileMbr.x1) * imageWidth / (fileMbr.x2 - fileMbr.x1));
        int s_y1 = (int) ((r.y1 - fileMbr.y1) * imageHeight / (fileMbr.y2 - fileMbr.y1));
        int s_x2 = (int) (((r.x2) - fileMbr.x1) * imageWidth / (fileMbr.x2 - fileMbr.x1));
        int s_y2 = (int) (((r.y2) - fileMbr.y1) * imageHeight / (fileMbr.y2 - fileMbr.y1));
        if (s_x1 >= 0 && s_x1 < imageWidth && s_y1 >= 0 && s_y1 < imageHeight)
            graphics.drawRect(s_x1, s_y1, s_x2 - s_x1 + 1, s_y2 - s_y1 + 1);
    }
}