Example usage for java.awt Graphics2D clearRect

List of usage examples for java.awt Graphics2D clearRect

Introduction

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

Prototype

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

Source Link

Document

Clears the specified rectangle by filling it with the background color of the current drawing surface.

Usage

From source file:org.sakaiproject.sitestats.impl.chart.ChartServiceImpl.java

private byte[] generateNoDataChart(int width, int height) {
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = img.createGraphics();

    g2d.setBackground(parseColor(M_sm.getChartBackgroundColor()));
    g2d.clearRect(0, 0, width - 1, height - 1);
    g2d.setColor(parseColor("#cccccc"));
    g2d.drawRect(0, 0, width - 1, height - 1);
    Font f = new Font("SansSerif", Font.PLAIN, 12);
    g2d.setFont(f);//from   w w  w  .j av  a2  s .  co  m
    FontMetrics fm = g2d.getFontMetrics(f);
    String noData = msgs.getString("no_data");
    int noDataWidth = fm.stringWidth(noData);
    int noDataHeight = fm.getHeight();
    g2d.setColor(parseColor("#555555"));
    g2d.drawString(noData, width / 2 - noDataWidth / 2, height / 2 - noDataHeight / 2 + 2);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", out);
    } catch (IOException e) {
        LOG.warn("Error occurred while generating SiteStats chart image data", e);
    }
    return out.toByteArray();
}

From source file:com.centurylink.mdw.designer.pages.ExportHelper.java

public byte[] printImage(float scale, CanvasCommon canvas, Dimension graphsize, String format)
        throws IOException {
    int h_margin = 72, v_margin = 72;
    BufferedImage image = new BufferedImage(graphsize.width + h_margin, graphsize.height + v_margin,
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    if (scale > 0)
        g2.scale(scale, scale);//from  w  w w.j av a2s . c o  m
    g2.setBackground(Color.WHITE);
    g2.clearRect(0, 0, image.getWidth(), image.getHeight());
    // canvas.paint(g2);
    Color bgsave = canvas.getBackground();
    boolean edsave = canvas.editable;
    canvas.editable = false;
    canvas.setBackground(Color.white);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    canvas.paintComponent(g2);
    canvas.setBackground(bgsave);
    canvas.editable = edsave;
    g2.dispose();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, format, baos);
    image = null;
    Runtime r = Runtime.getRuntime();
    r.gc();
    return baos.toByteArray();
}

From source file:com.centurylink.mdw.designer.pages.ExportHelper.java

public void printImage(String filename, float scale, CanvasCommon canvas, Dimension graphsize) {
    try {/*from   w w w. jav a2 s  . com*/
        int h_margin = 72, v_margin = 72;
        BufferedImage image = new BufferedImage(graphsize.width + h_margin, graphsize.height + v_margin,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        if (scale > 0)
            g2.scale(scale, scale);
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, image.getWidth(), image.getHeight());
        // canvas.paint(g2);
        Color bgsave = canvas.getBackground();
        canvas.setBackground(Color.white);
        canvas.paintComponent(g2);
        canvas.setBackground(bgsave);
        g2.dispose();
        ImageIO.write(image, "jpeg", new File(filename));
        image = null;
        Runtime r = Runtime.getRuntime();
        r.gc();
    } catch (IOException e) {
        System.err.println(e);
    }
}

From source file:org.sakaiproject.sitestats.impl.ServerWideReportManagerImpl.java

private byte[] generateNoDataChart(int width, int height) {
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = img.createGraphics();

    g2d.setBackground(parseColor(statsManager.getChartBackgroundColor()));
    g2d.clearRect(0, 0, width - 1, height - 1);
    g2d.setColor(parseColor("#cccccc"));
    g2d.drawRect(0, 0, width - 1, height - 1);
    Font f = new Font("SansSerif", Font.PLAIN, 12);
    g2d.setFont(f);/*from   w w w  . j av  a2s  .c o  m*/
    FontMetrics fm = g2d.getFontMetrics(f);
    String noData = msgs.getString("no_data");
    int noDataWidth = fm.stringWidth(noData);
    int noDataHeight = fm.getHeight();
    g2d.setColor(parseColor("#555555"));
    g2d.drawString(noData, width / 2 - noDataWidth / 2, height / 2 - noDataHeight / 2 + 2);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", out);
    } catch (IOException e) {
        log.warn("Error occurred while generating SiteStats chart image data", e);
    }
    return out.toByteArray();
}

From source file:lucee.runtime.img.Image.java

public void translate(int xtrans, int ytrans, Object interpolation) throws ExpressionException {

    RenderingHints hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, interpolation);
    if (interpolation != RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR) {
        hints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER, BorderExtender.createInstance(1)));
    }/*from www  . j a va 2 s .  c o m*/

    ParameterBlock pb = new ParameterBlock();
    pb.addSource(image());
    BufferedImage img = JAI.create("translate", pb).getAsBufferedImage();
    Graphics2D graphics = img.createGraphics();
    graphics.clearRect(0, 0, img.getWidth(), img.getHeight());
    AffineTransform at = new AffineTransform();
    at.setToIdentity();
    graphics.drawImage(image(), new AffineTransformOp(at, hints), xtrans, ytrans);
    graphics.dispose();
    image(img);
}

From source file:MyJava3D.java

public Graphics2D createGraphics2D(int width, int height, BufferedImage bi, Graphics g) {

    Graphics2D g2 = null;

    if (bi != null) {
        g2 = bi.createGraphics();//from   ww  w .  j  a  v  a2  s . co  m
    } else {
        g2 = (Graphics2D) g;
    }

    g2.setBackground(getBackground());
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, AntiAlias);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, Rendering);

    if (clearSurface || clearOnce) {
        g2.clearRect(0, 0, width, height);
        clearOnce = false;
    }

    if (texture != null) {
        // set composite to opaque for texture fills
        g2.setComposite(AlphaComposite.SrcOver);
        g2.setPaint(texture);
        g2.fillRect(0, 0, width, height);
    }

    if (composite != null) {
        g2.setComposite(composite);
    }

    return g2;
}

From source file:org.rdv.viz.chart.ChartPanel.java

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

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

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

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

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

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

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

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

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

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

            this.refreshBuffer = false; // clear the flag

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

            Graphics2D bufferG2 = (Graphics2D) this.chartBuffer.getGraphics();
            if (clearBuffer) {
                bufferG2.clearRect(0, 0, this.chartBufferWidth, this.chartBufferHeight);
            }
            if (scale) {
                AffineTransform saved = bufferG2.getTransform();
                AffineTransform st = AffineTransform.getScaleInstance(this.scaleX, this.scaleY);
                bufferG2.transform(st);
                this.chart.draw(bufferG2, chartArea, this.anchor, this.info);
                bufferG2.setTransform(saved);
            } else {
                this.chart.draw(bufferG2, bufferArea, this.anchor, this.info);
            }

        }

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

    }

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

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

    }

    // Redraw the zoom rectangle (if present)
    drawZoomRectangle(g2);

    g2.dispose();

    this.anchor = null;
    this.verticalTraceLine = null;
    this.horizontalTraceLine = null;

}

From source file:Thumbnail.java

/**
* Reads an image in a file and creates a thumbnail in another file.
* largestDimension is the largest dimension of the thumbnail, the other dimension is scaled accordingly.
* Utilises weighted stepping method to gradually reduce the image size for better results,
* i.e. larger steps to start with then smaller steps to finish with.
* Note: always writes a JPEG because GIF is protected or something - so always make your outFilename end in 'jpg'.
* PNG's with transparency are given white backgrounds
*//*from  ww w.  ja  v  a 2s  . co m*/
public String createThumbnail(String inFilename, String outFilename, int largestDimension) {
    try {
        double scale;
        int sizeDifference, originalImageLargestDim;
        if (!inFilename.endsWith(".jpg") && !inFilename.endsWith(".jpeg") && !inFilename.endsWith(".gif")
                && !inFilename.endsWith(".png")) {
            return "Error: Unsupported image type, please only either JPG, GIF or PNG";
        } else {
            Image inImage = Toolkit.getDefaultToolkit().getImage(inFilename);
            if (inImage.getWidth(null) == -1 || inImage.getHeight(null) == -1) {
                return "Error loading file: \"" + inFilename + "\"";
            } else {
                //find biggest dimension       
                if (inImage.getWidth(null) > inImage.getHeight(null)) {
                    scale = (double) largestDimension / (double) inImage.getWidth(null);
                    sizeDifference = inImage.getWidth(null) - largestDimension;
                    originalImageLargestDim = inImage.getWidth(null);
                } else {
                    scale = (double) largestDimension / (double) inImage.getHeight(null);
                    sizeDifference = inImage.getHeight(null) - largestDimension;
                    originalImageLargestDim = inImage.getHeight(null);
                }
                //create an image buffer to draw to
                BufferedImage outImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); //arbitrary init so code compiles
                Graphics2D g2d;
                AffineTransform tx;
                if (scale < 1.0d) //only scale if desired size is smaller than original
                {
                    int numSteps = sizeDifference / 100;
                    int stepSize = sizeDifference / numSteps;
                    int stepWeight = stepSize / 2;
                    int heavierStepSize = stepSize + stepWeight;
                    int lighterStepSize = stepSize - stepWeight;
                    int currentStepSize, centerStep;
                    double scaledW = inImage.getWidth(null);
                    double scaledH = inImage.getHeight(null);
                    if (numSteps % 2 == 1) //if there's an odd number of steps
                        centerStep = (int) Math.ceil((double) numSteps / 2d); //find the center step
                    else
                        centerStep = -1; //set it to -1 so it's ignored later
                    Integer intermediateSize = originalImageLargestDim,
                            previousIntermediateSize = originalImageLargestDim;
                    Integer calculatedDim;
                    for (Integer i = 0; i < numSteps; i++) {
                        if (i + 1 != centerStep) //if this isn't the center step
                        {
                            if (i == numSteps - 1) //if this is the last step
                            {
                                //fix the stepsize to account for decimal place errors previously
                                currentStepSize = previousIntermediateSize - largestDimension;
                            } else {
                                if (numSteps - i > numSteps / 2) //if we're in the first half of the reductions
                                    currentStepSize = heavierStepSize;
                                else
                                    currentStepSize = lighterStepSize;
                            }
                        } else //center step, use natural step size
                        {
                            currentStepSize = stepSize;
                        }
                        intermediateSize = previousIntermediateSize - currentStepSize;
                        scale = (double) intermediateSize / (double) previousIntermediateSize;
                        scaledW = (int) scaledW * scale;
                        scaledH = (int) scaledH * scale;
                        outImage = new BufferedImage((int) scaledW, (int) scaledH, BufferedImage.TYPE_INT_RGB);
                        g2d = outImage.createGraphics();
                        g2d.setBackground(Color.WHITE);
                        g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
                        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                        tx = new AffineTransform();
                        tx.scale(scale, scale);
                        g2d.drawImage(inImage, tx, null);
                        g2d.dispose();
                        inImage = new ImageIcon(outImage).getImage();
                        previousIntermediateSize = intermediateSize;
                    }
                } else {
                    //just copy the original
                    outImage = new BufferedImage(inImage.getWidth(null), inImage.getHeight(null),
                            BufferedImage.TYPE_INT_RGB);
                    g2d = outImage.createGraphics();
                    g2d.setBackground(Color.WHITE);
                    g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
                    tx = new AffineTransform();
                    tx.setToIdentity(); //use identity matrix so image is copied exactly
                    g2d.drawImage(inImage, tx, null);
                    g2d.dispose();
                }
                //JPEG-encode the image and write to file.
                OutputStream os = new FileOutputStream(outFilename);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
                encoder.encode(outImage);
                os.close();
            }
        }
    } catch (Exception ex) {
        String errorMsg = "";
        errorMsg += "<br>Exception: " + ex.toString();
        errorMsg += "<br>Cause = " + ex.getCause();
        errorMsg += "<br>Stack Trace = ";
        StackTraceElement stackTrace[] = ex.getStackTrace();
        for (int traceLine = 0; traceLine < stackTrace.length; traceLine++) {
            errorMsg += "<br>" + stackTrace[traceLine];
        }
        return errorMsg;
    }
    return ""; //success
}

From source file:org.apache.fop.render.pcl.PCLDocumentHandler.java

private IFPainter createAllBitmapPainter() {
    double scale = gen.getMaximumBitmapResolution() / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION;
    Rectangle printArea = this.currentPageDefinition.getLogicalPageRect();
    int bitmapWidth = (int) Math.ceil(UnitConv.mpt2px(printArea.width, gen.getMaximumBitmapResolution()));
    int bitmapHeight = (int) Math.ceil(UnitConv.mpt2px(printArea.height, gen.getMaximumBitmapResolution()));
    this.currentImage = createBufferedImage(bitmapWidth, bitmapHeight);
    Graphics2D graphics2D = this.currentImage.createGraphics();

    if (!PCLGenerator.isJAIAvailable()) {
        RenderingHints hints = new RenderingHints(null);
        //These hints don't seem to make a difference :-( Not seeing any dithering on Sun Java.
        hints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        graphics2D.addRenderingHints(hints);
    }/*w ww . ja  va2 s.co m*/

    //Ensure white page background
    graphics2D.setBackground(Color.WHITE);
    graphics2D.clearRect(0, 0, bitmapWidth, bitmapHeight);

    graphics2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
            RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
    graphics2D.scale(scale / 1000f, scale / 1000f);
    graphics2D.translate(-printArea.x, -printArea.y);

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

From source file:org.apache.fop.render.pcl.PCLPainter.java

private void drawTextAsBitmap(final int x, final int y, final int letterSpacing, final int wordSpacing,
        final int[] dx, final String text, FontTriplet triplet) throws IFException {
    //Use Java2D to paint different fonts via bitmap
    final Font font = parent.getFontInfo().getFontInstance(triplet, state.getFontSize());

    //for cursive fonts, so the text isn't clipped
    final FontMetricsMapper mapper = (FontMetricsMapper) parent.getFontInfo().getMetricsFor(font.getFontName());
    final int maxAscent = mapper.getMaxAscent(font.getFontSize()) / 1000;
    final int ascent = mapper.getAscender(font.getFontSize()) / 1000;
    final int descent = mapper.getDescender(font.getFontSize()) / 1000;
    int safetyMargin = (int) (SAFETY_MARGIN_FACTOR * font.getFontSize());
    final int baselineOffset = maxAscent + safetyMargin;

    final Rectangle boundingBox = getTextBoundingBox(x, y, letterSpacing, wordSpacing, dx, text, font, mapper);
    final Dimension dim = boundingBox.getSize();

    Graphics2DImagePainter painter = new Graphics2DImagePainter() {

        public void paint(Graphics2D g2d, Rectangle2D area) {
            if (DEBUG) {
                g2d.setBackground(Color.LIGHT_GRAY);
                g2d.clearRect(0, 0, (int) area.getWidth(), (int) area.getHeight());
            }//  www.ja  v  a 2  s.c  o m
            g2d.translate(-x, -y + baselineOffset);

            if (DEBUG) {
                Rectangle rect = new Rectangle(x, y - maxAscent, 3000, maxAscent);
                g2d.draw(rect);
                rect = new Rectangle(x, y - ascent, 2000, ascent);
                g2d.draw(rect);
                rect = new Rectangle(x, y, 1000, -descent);
                g2d.draw(rect);
            }
            Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state);
            try {
                painter.drawText(x, y, letterSpacing, wordSpacing, dx, text);
            } catch (IFException e) {
                //This should never happen with the Java2DPainter
                throw new RuntimeException("Unexpected error while painting text", e);
            }
        }

        public Dimension getImageSize() {
            return dim.getSize();
        }

    };
    paintMarksAsBitmap(painter, boundingBox);
}