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.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private void generaImagenDamage(ShapeView fondo, List<DamageDetailsVB> danios, File outputfile, int width,
        int height) {
    try {/*from w  ww. j  av a  2s  .co  m*/
        Point contexto = new Point((width - fondo.getShapeWidth()) / 2, (height - fondo.getShapeHeight()) / 2);
        BufferedImage off_Image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = off_Image.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, width, height);
        AffineTransform saveXform = g2.getTransform();
        AffineTransform toCenterAt = new AffineTransform();
        toCenterAt.translate(contexto.getX(), contexto.getY());
        g2.transform(toCenterAt);
        fondo.paint(g2);
        g2.setTransform(saveXform);
        for (DamageDetailsVB x : danios) {
            DamageDetailGraphicsView obj = new DamageDetailGraphicsView();
            obj.setPosicion(new Point(x.getX(), x.getY()));
            obj.setContexto(contexto);
            if (x.getX() <= fondo.getShapeWidth() / 2) {
                if (x.getY() <= fondo.getShapeHeight() / 2) {
                    obj.setOrientacion(DamageDetailGraphicsView.SuperiorIzquierda);
                } else {
                    obj.setOrientacion(DamageDetailGraphicsView.InferiorIzquierda);
                }
            } else {
                if (x.getY() <= fondo.getShapeHeight() / 2) {
                    obj.setOrientacion(DamageDetailGraphicsView.SuperiorDerecha);
                } else {
                    obj.setOrientacion(DamageDetailGraphicsView.InferiorDerecha);
                }
            }
            obj.setCategoria(x.getCategoria());
            obj.setCaracteristica(x.getCaracteristica());
            obj.paint(g2);
        }
        saveJPG(off_Image, outputfile);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.yes.cart.service.domain.impl.ImageServiceImpl.java

/**
 * {@inheritDoc}/*  w w w .j  a va2  s .co m*/
 */
public byte[] resizeImage(final String filename, final byte[] content, final String width, final String height,
        final boolean cropToFit) {

    try {

        final InputStream bis = new ByteArrayInputStream(content);

        final BufferedImage originalImg = ImageIO.read(bis);
        final String codec = getCodecFromFilename(filename);
        final boolean supportsAlpha = hasAlphaSupport(codec);

        int x = NumberUtils.toInt(width);
        int y = NumberUtils.toInt(height);
        int originalX = originalImg.getWidth();
        int originalY = originalImg.getHeight();

        boolean doCropToFit = cropToFit || x < forceCropToFitOnSize || y < forceCropToFitOnSize;

        final int imageType = originalImg.getType();

        final Image resizedImg;
        //            final BufferedImage resizedImg;
        final int padX, padY;
        if (doCropToFit) {
            // crop the original to best fit of target size
            int[] cropDims = cropImageToCenter(x, y, originalX, originalY);
            padX = 0;
            padY = 0;

            final BufferedImage croppedImg = originalImg.getSubimage(cropDims[0], cropDims[1], cropDims[2],
                    cropDims[3]);
            resizedImg = croppedImg.getScaledInstance(x, y, Image.SCALE_SMOOTH);

            //                final BufferedImage croppedImg = originalImg.getSubimage(cropDims[0], cropDims[1], cropDims[2], cropDims[3]);
            //                resizedImg = new BufferedImage(y, x, imageType);
            //                Graphics2D graphics = resizedImg.createGraphics();
            //                graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            //                graphics.drawImage(croppedImg, 0, 0, x, y, null);
        } else {
            int[] scaleDims = scaleImageToCenter(x, y, originalX, originalY);
            padX = scaleDims[0];
            padY = scaleDims[1];

            resizedImg = originalImg.getScaledInstance(scaleDims[2], scaleDims[3], Image.SCALE_SMOOTH);

            //                resizedImg = new BufferedImage(scaleDims[3], scaleDims[2], imageType);
            //                Graphics2D graphics = resizedImg.createGraphics();
            //                graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            //                graphics.drawImage(originalImg, 0, 0, scaleDims[2], scaleDims[3], null);
        }

        // base canvas
        final BufferedImage resizedImgFinal = new BufferedImage(x, y, imageType);

        // fill base color
        final Graphics2D graphics = resizedImgFinal.createGraphics();
        graphics.setPaint(supportsAlpha ? alphaBorder : defaultBorder);
        graphics.fillRect(0, 0, x, y);

        // insert scaled image
        graphics.drawImage(resizedImg, padX, padY, null);

        final ByteArrayOutputStream bos = new ByteArrayOutputStream();

        ImageIO.write(resizedImgFinal, codec, bos);

        return bos.toByteArray();

    } catch (Exception exp) {
        ShopCodeContext.getLog(this).error("Unable to resize image " + filename, exp);
    }

    return new byte[0];

}

From source file:algorithm.QRCodeWatermarking.java

/**
 * Creates a PNG image that contains the QR-code with the information from
 * the payload file. The image has the same name as the payload file.
 * //from w ww .  j  a  v  a2  s .c  om
 * @param payload
 * @return qr code as png image file
 * @throws IOException
 */
private File createBarcodeFile(File payload, String imageFormat, String usedMethod) throws IOException {
    // Create restoration metadata only for the payload file to spare space.
    PayloadSegment metadata = new PayloadSegment(payload);
    metadata.addOptionalProperty("usedMethod", usedMethod);
    byte[] payloadSegment = metadata.getPayloadSegmentBytes();
    String barcodeInformation = new String(payloadSegment);
    int size = getQRCodeSize();
    String outputFileName = FilenameUtils.removeExtension(getOutputFileName(payload)) + "." + imageFormat;
    File outputFile = new File(outputFileName);
    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
    BitMatrix byteMatrix = encodeWithQRCode(barcodeInformation, hintMap, size);
    if (byteMatrix == null) {
        return null;
    }
    BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
    image.createGraphics();
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setColor(Color.WHITE);
    graphics.fillRect(0, 0, size, size);
    graphics.setColor(Color.BLACK);
    for (int x = 0; x < size; x++) {
        for (int y = 0; y < size; y++) {
            if (byteMatrix.get(x, y)) {
                graphics.fillRect(x, y, 1, 1);
            }
        }
    }
    ImageIO.write(image, imageFormat, outputFile);
    return outputFile;
}

From source file:net.team2xh.crt.gui.editor.EditorTextPane.java

/**
 * Paints the background, the margin background and the margin line.
 *
 * @param g//w w  w . j  ava 2s.co m
 */
@Override
public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    int m = marginSize;
    int w = getWidth(), h = getHeight();
    // Background
    g2d.setPaint(Theme.getTheme().COLOR_02);
    g2d.fillRect(0, 0, m, h);
    // Margin background
    if (m < w) {
        g2d.setColor(Theme.getTheme().COLOR_01);
        g2d.fillRect(m, 0, w - m, h);
    }
    // Margin line
    g2d.setColor(Theme.getTheme().COLOR_04);
    g2d.drawLine(m, 0, m, h);
    // Draw the rest
    super.paintComponent(g);
}

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

/**
 * Draw a legend which consists of the given bases arranged horizontally
 *///from   w w  w .j  a  va2s. c  o m
protected void drawBaseLegend(Graphics2D g2, int x, int y, ColourKey... keys) {
    ColourScheme cs = (ColourScheme) instructions.get(DrawingInstruction.COLOUR_SCHEME);
    g2.setFont(LEGEND_FONT);

    for (ColourKey k : keys) {
        g2.setColor(cs.getColor(k));
        g2.fillRect(x, y - SWATCH_SIZE.height + 2, SWATCH_SIZE.width, SWATCH_SIZE.height);
        g2.setColor(Color.BLACK);
        g2.drawString(k.getName(), x + SWATCH_SIZE.width + 3, y);
        x += 27;
    }
}

From source file:savant.view.variation.swing.VariantMap.java

@Override
public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // Paint a gradient from top to bottom
    int h = getHeight();
    int w = getWidth();
    GradientPaint gp0 = new GradientPaint(0, 0, ColourSettings.getColor(ColourKey.GRAPH_PANE_BACKGROUND_TOP), 0,
            h, ColourSettings.getColor(ColourKey.GRAPH_PANE_BACKGROUND_BOTTOM));
    g2.setPaint(gp0);// ww  w  .  j  av a 2 s . co  m
    g2.fillRect(0, 0, w, h);

    List<VariantRecord> data = controller.getData();
    if (data != null && !data.isEmpty()) {
        double boxTop = Double.NaN;
        double boxBottom = Double.NaN;
        Range browseRange = LocationController.getInstance().getRange();

        int participantCount = controller.getParticipantCount();
        unitHeight = (double) h / data.size();
        unitWidth = (double) w / participantCount;

        boolean gappable = unitHeight > GAP_HEIGHT * 2.0;

        ColourScheme cs = new ColourScheme(ColourKey.A, ColourKey.C, ColourKey.G, ColourKey.T,
                ColourKey.INSERTED_BASE, ColourKey.DELETED_BASE, ColourKey.N);
        ColourAccumulator accumulator = new ColourAccumulator(cs);

        double y = 0.0;
        double topGap = 0.0;
        for (int i = 0; i < data.size(); i++) {
            VariantRecord varRec = data.get(i);

            double bottomGap = 0.0;
            if (gappable && i + 1 < data.size()) {
                VariantRecord nextRec = data.get(i + 1);
                if (nextRec.getPosition() - varRec.getPosition() > 1) {
                    bottomGap = GAP_HEIGHT * 0.5;
                }
            }

            if (Double.isNaN(boxTop) && browseRange.getFrom() <= varRec.getPosition()
                    && browseRange.getTo() >= varRec.getPosition()) {
                boxTop = y + topGap;
                boxBottom = boxTop + unitHeight;
            } else if (varRec.getPosition() <= browseRange.getTo()) {
                boxBottom = y + unitHeight - bottomGap;
            }
            double x = 0.0;
            for (int j = 0; j < participantCount; j++) {
                VariantTrackRenderer.accumulateZygoteShapes(varRec.getVariantsForParticipant(j), accumulator,
                        new Rectangle2D.Double(x, y + topGap, unitWidth, unitHeight - topGap - bottomGap));
                x += unitWidth;
            }
            topGap = bottomGap;
            y += unitHeight;
        }
        accumulator.fill(g2);

        if (gappable) {
            drawGapSizes(g2);
        } else {
            // Not enough room to draw gaps, so just label the axes.
            labelVerticalAxis(g2);
        }

        g2.setClip(null);
        g2.setColor(Color.BLUE);
        g2.draw(new Rectangle2D.Double(0.0, boxTop, w - 1.0, boxBottom - boxTop - 1.0));
    }
}

From source file:com.nbt.TileCanvas.java

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

    Graphics2D g2d = (Graphics2D) g.create();

    g2d.setColor(Color.BLACK);/*from w ww  .  java2 s. c o m*/
    int x = 0, y = 0;
    Dimension size = getSize();
    g2d.fillRect(x, y, size.width, size.height);

    final int altitude = getAltitude();
    for (int w = 0; w < getTileWidth(); w++) {
        x = w * SPRITE_SIZE;
        for (int h = 0; h < getTileHeight(); h++) {
            y = h * SPRITE_SIZE;

            int xOffset = w + getTileX();
            int zOffset = h + getTileZ();
            BufferedImage tile = getBackgroundTile(xOffset, altitude, zOffset);
            if (tile != null)
                g2d.drawImage(tile, x, y, null);
        }
    }

    g2d.dispose();
}

From source file:org.apache.fop.render.bitmap.AbstractBitmapDocumentHandler.java

/** {@inheritDoc} */
public IFPainter startPageContent() throws IFException {
    int bitmapWidth;
    int bitmapHeight;
    double scale;
    Point2D offset = null;/*from   w  w  w.  j a va  2 s  .  com*/
    if (targetBitmapSize != null) {
        //Fit the generated page proportionally into the given rectangle (in pixels)
        double scale2w = 1000 * targetBitmapSize.width / this.currentPageDimensions.getWidth();
        double scale2h = 1000 * targetBitmapSize.height / this.currentPageDimensions.getHeight();
        bitmapWidth = targetBitmapSize.width;
        bitmapHeight = targetBitmapSize.height;

        //Centering the page in the given bitmap
        offset = new Point2D.Double();
        if (scale2w < scale2h) {
            scale = scale2w;
            double h = this.currentPageDimensions.height * scale / 1000;
            offset.setLocation(0, (bitmapHeight - h) / 2.0);
        } else {
            scale = scale2h;
            double w = this.currentPageDimensions.width * scale / 1000;
            offset.setLocation((bitmapWidth - w) / 2.0, 0);
        }
    } else {
        //Normal case: just scale according to the target resolution
        scale = scaleFactor * getUserAgent().getTargetResolution()
                / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION;
        bitmapWidth = (int) ((this.currentPageDimensions.width * scale / 1000f) + 0.5f);
        bitmapHeight = (int) ((this.currentPageDimensions.height * scale / 1000f) + 0.5f);
    }

    //Set up bitmap to paint on
    this.currentImage = createBufferedImage(bitmapWidth, bitmapHeight);
    Graphics2D graphics2D = this.currentImage.createGraphics();

    // draw page background
    if (!getSettings().hasTransparentPageBackground()) {
        graphics2D.setBackground(getSettings().getPageBackgroundColor());
        graphics2D.setPaint(getSettings().getPageBackgroundColor());
        graphics2D.fillRect(0, 0, bitmapWidth, bitmapHeight);
    }

    //Set rendering hints
    graphics2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
            RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    if (getSettings().isAntiAliasingEnabled() && this.currentImage.getColorModel().getPixelSize() > 1) {
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    } else {
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
        graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    }
    if (getSettings().isQualityRenderingEnabled()) {
        graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    } else {
        graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
    }
    graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

    //Set up initial coordinate system for the page
    if (offset != null) {
        graphics2D.translate(offset.getX(), offset.getY());
    }
    graphics2D.scale(scale / 1000f, scale / 1000f);

    return new Java2DPainter(graphics2D, getContext(), getFontInfo());
}

From source file:org.kuali.mobility.people.service.PeopleServiceImpl.java

@Override
public BufferedImage generateObfuscatedImage(String text) {
    int width = 250;
    int height = 25;

    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2d = bufferedImage.createGraphics();
    Font font = new Font("Arial", Font.PLAIN, 14);
    g2d.setFont(font);//from   www  .  j a v  a2s.  c om

    RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    g2d.setRenderingHints(rh);

    Paint bg = new Color(255, 255, 255);
    g2d.setPaint(bg);
    g2d.fillRect(0, 0, width, height);

    int x = 0;
    int y = height - 7;

    Paint textPaint = new Color(0, 0, 0);
    g2d.setPaint(textPaint);
    g2d.drawString(text, x, y);

    g2d.dispose();
    return bufferedImage;
}

From source file:edu.ku.brc.ui.dnd.SimpleGlassPane.java

@Override
protected void paintComponent(Graphics graphics) {
    Graphics2D g = (Graphics2D) graphics;

    Rectangle rect = getInternalBounds();
    int width = rect.width;
    int height = rect.height;

    if (useBGImage) {
        // Create a translucent intermediate image in which we can perform
        // the soft clipping
        GraphicsConfiguration gc = g.getDeviceConfiguration();
        if (img == null || img.getWidth() != width || img.getHeight() != height) {
            img = gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        }//w w  w. ja v a 2s  .  c  om
        Graphics2D g2 = img.createGraphics();

        // Clear the image so all pixels have zero alpha
        g2.setComposite(AlphaComposite.Clear);
        g2.fillRect(0, 0, width, height);

        g2.setComposite(AlphaComposite.Src);
        g2.setColor(new Color(0, 0, 0, 85));
        g2.fillRect(0, 0, width, height);

        if (delegateRenderer != null) {
            delegateRenderer.render(g, g2, img);
        }

        g2.dispose();

        // Copy our intermediate image to the screen
        g.drawImage(img, rect.x, rect.y, null);
    }

    super.paintComponent(graphics);

    if (StringUtils.isNotEmpty(text)) {
        Graphics2D g2 = (Graphics2D) graphics;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(fillColor);
        g2.fillRect(margin.left, margin.top, rect.width, rect.height);

        g2.setFont(new Font((new JLabel()).getFont().getName(), Font.BOLD, pointSize));
        FontMetrics fm = g2.getFontMetrics();

        int tw = fm.stringWidth(text);
        int th = fm.getHeight();
        int tx = (rect.width - tw) / 2;
        int ty = (rect.height - th) / 2;

        if (yPos != null) {
            ty = yPos;
        }

        int expand = 20;
        int arc = expand * 2;

        g2.setColor(new Color(0, 0, 0, 50));

        int x = margin.left + tx - (expand / 2);
        int y = margin.top + ty - fm.getAscent() - (expand / 2);

        drawBGContainer(g2, true, x + 4, y + 6, tw + expand, th + expand, arc, arc);

        g2.setColor(new Color(255, 255, 255, 220));
        drawBGContainer(g2, true, x, y, tw + expand, th + expand, arc, arc);

        g2.setColor(Color.DARK_GRAY);
        drawBGContainer(g2, false, x, y, tw + expand, th + expand, arc, arc);

        g2.setColor(textColor == null ? Color.BLACK : textColor);
        g2.drawString(text, tx, ty);
    }
}