Example usage for java.awt Graphics2D drawString

List of usage examples for java.awt Graphics2D drawString

Introduction

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

Prototype

public abstract void drawString(AttributedCharacterIterator iterator, float x, float y);

Source Link

Document

Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.

Usage

From source file:c.depthchart.ViewerPanel.java

private void writeStats(Graphics2D g2)
/* write statistics in bottom-left corner, or
   "Loading" at start time */// w  w w.j  av a2s. c  o  m
{
    g2.setColor(Color.BLUE);
    g2.setFont(msgFont);
    int panelHeight = getHeight();
    if (imageCount > 0) {
        double avgGrabTime = (double) totalTime / imageCount;
        g2.drawString("Pic " + imageCount + "  " + df.format(avgGrabTime) + " ms", 5, panelHeight - 10); // bottom left
    } else // no image yet
        g2.drawString("Loading...", 5, panelHeight - 10);
}

From source file:org.jrecruiter.service.impl.DataServiceImpl.java

/** {@inheritDoc} */
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Image getGoogleMapImage(final BigDecimal latitude, final BigDecimal longitude, final Integer zoomLevel) {

    if (longitude == null) {
        throw new IllegalArgumentException("Longitude cannot be null.");
    }/* w  w w  . jav a 2s  .  c o m*/

    if (latitude == null) {
        throw new IllegalArgumentException("Latitude cannot be null.");
    }

    if (zoomLevel == null) {
        throw new IllegalArgumentException("ZoomLevel cannot be null.");
    }

    final URI url = GoogleMapsUtils.buildGoogleMapsStaticUrl(latitude, longitude, zoomLevel);

    BufferedImage img;
    try {
        URLConnection conn = url.toURL().openConnection();
        img = ImageIO.read(conn.getInputStream());
    } catch (UnknownHostException e) {
        LOGGER.error("Google static MAPS web service is not reachable (UnknownHostException).", e);
        img = new BufferedImage(GoogleMapsUtils.defaultWidth, 100, BufferedImage.TYPE_INT_RGB);

        final Graphics2D graphics = img.createGraphics();

        final Map<Object, Object> renderingHints = CollectionUtils.getHashMap();
        renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        graphics.addRenderingHints(renderingHints);
        graphics.setBackground(Color.WHITE);
        graphics.setColor(Color.GRAY);
        graphics.clearRect(0, 0, GoogleMapsUtils.defaultWidth, 100);

        graphics.drawString("Not Available", 30, 30);

    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

    return img;
}

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

/**
 * renders one frame of the animation./*from   w  ww  .  java2  s . c  o  m*/
 */
private Image renderFrame(ITimePosition[] sortedTimeArray, int currentTimeIndex, int screenW, int screenH,
        IBoundingBox bbox, Set<OXFFeature> selectedFeatures, ObservationSeriesCollection obsValues) {
    ContextBoundingBox contextBBox = new ContextBoundingBox(bbox);

    BufferedImage image = new BufferedImage(screenW, screenH, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = image.createGraphics();

    ITimePosition currentTimePos = sortedTimeArray[currentTimeIndex];

    // draw white background:
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, screenW, screenH);

    // draw time-string into map:
    g.setColor(Color.BLACK);
    g.drawString(currentTimePos.toString(), 20, 20);

    for (OXFFeature dotFeature : selectedFeatures) {

        //
        // draw the points into the image at the georeferenced position of the corresponding feature:
        //
        Point pRealWorld = (Point) dotFeature.getGeometry();

        java.awt.Point pScreen = ContextBoundingBox.realworld2Screen(contextBBox.getActualBBox(), screenW,
                screenH, new Point2D.Double(pRealWorld.getCoordinate().x, pRealWorld.getCoordinate().y));

        ObservedValueTuple tuple = obsValues.getTuple(dotFeature, currentTimePos);

        // if there wasn't a tuple for the current time position go backwards through the sortedTimeArray and take the most recent one:
        int j = currentTimeIndex - 1;
        while (tuple == null && j >= 0) {
            tuple = obsValues.getTuple(dotFeature, sortedTimeArray[j]);
            j--;
        }

        // if a tuple was found -> draw the dot:
        if (tuple != null) {
            int dotSize = computeDotSize((Double) tuple.getValue(0), (Double) obsValues.getMinimum(0),
                    (Double) obsValues.getMaximum(0));
            g.setColor(POINT_INNER_COLOR);
            g.fillOval(pScreen.x - (dotSize / 2), pScreen.y - (dotSize / 2), dotSize, dotSize);
        }
        // otherwise draw "no data available"
        else {
            g.setColor(Color.BLACK);

            // draw point of feature:
            g.fillOval(pScreen.x - (FeatureGeometryRenderer.DOT_SIZE_POINT / 2),
                    pScreen.y - (FeatureGeometryRenderer.DOT_SIZE_POINT / 2),
                    FeatureGeometryRenderer.DOT_SIZE_POINT, FeatureGeometryRenderer.DOT_SIZE_POINT);

            g.drawString("No data available", pScreen.x + X_SHIFT, pScreen.y + Y_SHIFT);
        }
    }

    return image;
}

From source file:CompositeEffects.java

/** Draw the example */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;

    // fill the background
    g.setPaint(new Color(175, 175, 175));
    g.fillRect(0, 0, getWidth(), getHeight());

    // Set text attributes
    g.setColor(Color.black);/*from  ww  w. ja v a 2 s .  com*/
    g.setFont(new Font("SansSerif", Font.BOLD, 12));

    // Draw the unmodified image
    g.translate(10, 10);
    g.drawImage(cover, 0, 0, this);
    g.drawString("SRC_OVER", 0, COVERHEIGHT + 15);

    // Draw the cover again, using AlphaComposite to make the opaque
    // colors of the image 50% translucent
    g.translate(COVERWIDTH + 10, 0);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
    g.drawImage(cover, 0, 0, this);

    // Restore the pre-defined default Composite for the screen, so
    // opaque colors stay opaque.
    g.setComposite(AlphaComposite.SrcOver);
    // Label the effect
    g.drawString("SRC_OVER, 50%", 0, COVERHEIGHT + 15);

    // Now get an offscreen image to work with. In order to achieve
    // certain compositing effects, the drawing surface must support
    // transparency. Onscreen drawing surfaces cannot, so we have to do the
    // compositing in an offscreen image that is specially created to have
    // an "alpha channel", then copy the final result to the screen.
    BufferedImage offscreen = new BufferedImage(COVERWIDTH, COVERHEIGHT, BufferedImage.TYPE_INT_ARGB);

    // First, fill the image with a color gradient background that varies
    // left-to-right from opaque to transparent yellow
    Graphics2D osg = offscreen.createGraphics();
    osg.setPaint(new GradientPaint(0, 0, Color.yellow, COVERWIDTH, 0, new Color(255, 255, 0, 0)));
    osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT);

    // Now copy the cover image on top of this, but use the DstOver rule
    // which draws it "underneath" the existing pixels, and allows the
    // image to show depending on the transparency of those pixels.
    osg.setComposite(AlphaComposite.DstOver);
    osg.drawImage(cover, 0, 0, this);

    // And display this composited image on the screen. Note that the
    // image is opaque and that none of the screen background shows through
    g.translate(COVERWIDTH + 10, 0);
    g.drawImage(offscreen, 0, 0, this);
    g.drawString("DST_OVER", 0, COVERHEIGHT + 15);

    // Now start over and do a new effect with the off-screen image.
    // First, fill the offscreen image with a new color gradient. We
    // don't care about the colors themselves; we just want the
    // translucency of the background to vary. We use opaque black to
    // transparent black. Note that since we've already used this offscreen
    // image, we set the composite to Src, we can fill the image and
    // ignore anything that is already there.
    osg.setComposite(AlphaComposite.Src);
    osg.setPaint(new GradientPaint(0, 0, Color.black, COVERWIDTH, COVERHEIGHT, new Color(0, 0, 0, 0)));
    osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT);

    // Now set the compositing type to SrcIn, so colors come from the
    // source, but translucency comes from the destination
    osg.setComposite(AlphaComposite.SrcIn);

    // Draw our loaded image into the off-screen image, compositing it.
    osg.drawImage(cover, 0, 0, this);

    // And then copy our off-screen image to the screen. Note that the
    // image is translucent and some of the image shows through.
    g.translate(COVERWIDTH + 10, 0);
    g.drawImage(offscreen, 0, 0, this);
    g.drawString("SRC_IN", 0, COVERHEIGHT + 15);

    // If we do the same thing but use SrcOut, then the resulting image
    // will have the inverted translucency values of the destination
    osg.setComposite(AlphaComposite.Src);
    osg.setPaint(new GradientPaint(0, 0, Color.black, COVERWIDTH, COVERHEIGHT, new Color(0, 0, 0, 0)));
    osg.fillRect(0, 0, COVERWIDTH, COVERHEIGHT);
    osg.setComposite(AlphaComposite.SrcOut);
    osg.drawImage(cover, 0, 0, this);
    g.translate(COVERWIDTH + 10, 0);
    g.drawImage(offscreen, 0, 0, this);
    g.drawString("SRC_OUT", 0, COVERHEIGHT + 15);

    // Here's a cool effect; it has nothing to do with compositing, but
    // uses an arbitrary shape to clip the image. It uses Area to combine
    // shapes into more complicated ones.
    g.translate(COVERWIDTH + 10, 0);
    Shape savedClip = g.getClip(); // Save current clipping region
    // Create a shape to use as the new clipping region.
    // Begin with an ellipse
    Area clip = new Area(new Ellipse2D.Float(0, 0, COVERWIDTH, COVERHEIGHT));
    // Intersect with a rectangle, truncating the ellipse.
    clip.intersect(new Area(new Rectangle(5, 5, COVERWIDTH - 10, COVERHEIGHT - 10)));
    // Then subtract an ellipse from the bottom of the truncated ellipse.
    clip.subtract(new Area(new Ellipse2D.Float(COVERWIDTH / 2 - 40, COVERHEIGHT - 20, 80, 40)));
    // Use the resulting shape as the new clipping region
    g.clip(clip);
    // Then draw the image through this clipping region
    g.drawImage(cover, 0, 0, this);
    // Restore the old clipping region so we can label the effect
    g.setClip(savedClip);
    g.drawString("Clipping", 0, COVERHEIGHT + 15);
}

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

private Image renderLegend(ObservationSeriesCollection obsValues, String observedProperty) {

    double lowestValue = (Double) obsValues.getMinimum(0);
    double highestValue = (Double) obsValues.getMaximum(0);

    double classDistance = (highestValue - lowestValue) / (NUMBER_OF_CLASSES - 2);
    int dotSizeDistance = (MAX_DOT_SIZE - MIN_DOT_SIZE) / (NUMBER_OF_CLASSES - 2);

    BufferedImage image = new BufferedImage(LEGEND_WIDTH, LEGEND_HEIGHT, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = image.createGraphics();

    // draw white background:
    g.setColor(Color.WHITE);//from   ww  w  .ja v  a 2s.c  o m
    g.fillRect(0, 0, LEGEND_WIDTH, LEGEND_HEIGHT);

    // draw information:
    observedProperty = observedProperty.split(":")[observedProperty.split(":").length - 1];
    g.setColor(Color.BLACK);
    g.drawString("Observed Property:   '" + observedProperty + "'", 25, 25);

    for (int i = 1; i <= NUMBER_OF_CLASSES; i++) {
        // draw text:
        int x_stringLocation = 100;
        int y_location = i * 60;
        g.setColor(Color.BLACK);

        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
        df.applyPattern("#,###,##0.00");

        double lowerBorder = lowestValue + classDistance * (i - 1);
        double upperBorder = lowestValue + classDistance * i;

        g.drawString(i + ". class: " + df.format(lowerBorder) + " - " + df.format(upperBorder),
                x_stringLocation, y_location + 10);

        // draw symbol:
        int x_symbolLocation = 30;
        g.setColor(POINT_INNER_COLOR);
        g.fillOval(x_symbolLocation, y_location, i * dotSizeDistance, i * dotSizeDistance);
    }

    return image;
}

From source file:org.squidy.designer.util.DrawableString.java

/**
 * @param g//  www.  ja v a  2  s  .  c  o m
 */
public void draw(Graphics2D g, double viewScale) {
    if (value == null)
        return;
    if (color != null)
        g.setColor(color);
    if (font != null)
        g.setFont(font);
    update(g, viewScale);
    if (drawValue != null)
        g.drawString(drawValue, positionX + offsetX, positionY + offsetY);
}

From source file:be.fedict.eid.idp.sp.PhotoServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    response.setContentType("image/jpg");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    HttpSession session = request.getSession();

    byte[] photoData = (byte[]) session.getAttribute(PHOTO_SESSION_ATTRIBUTE);

    if (null != photoData) {
        BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData));
        if (null == photo) {
            /*/*from   w w  w.ja v a 2 s.c o  m*/
             * In this case we render a photo containing some error message.
             */
            photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) photo.getGraphics();
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setRenderingHints(renderingHints);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
            graphics.setColor(Color.RED);
            graphics.setFont(new Font("Dialog", Font.BOLD, 20));
            graphics.drawString("Photo Error", 0, 200 / 2);
            graphics.dispose();
            ImageIO.write(photo, "jpg", out);
        } else {
            out.write(photoData);
        }
    }
    out.close();
}

From source file:be.fedict.eid.applet.service.PhotoServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    response.setContentType("image/jpg");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    HttpSession session = request.getSession();
    byte[] photoData = (byte[]) session.getAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE);
    if (null != photoData) {
        BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData));
        if (null == photo) {
            /*/*ww  w.  java2s .c  om*/
             * In this case we render a photo containing some error message.
             */
            photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) photo.getGraphics();
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setRenderingHints(renderingHints);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
            graphics.setColor(Color.RED);
            graphics.setFont(new Font("Dialog", Font.BOLD, 20));
            graphics.drawString("Photo Error", 0, 200 / 2);
            graphics.dispose();
            ImageIO.write(photo, "jpg", out);
        } else {
            out.write(photoData);
        }
    }
    out.close();
}

From source file:IteratorTest.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    String s = "Java Source and Support";
    Dimension d = getSize();//from   w  ww  .j  a v a 2  s .c  o m

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    Font serifFont = new Font("Serif", Font.PLAIN, 48);
    Font sansSerifFont = new Font("Monospaced", Font.PLAIN, 48);

    AttributedString as = new AttributedString(s);
    as.addAttribute(TextAttribute.FONT, serifFont);
    as.addAttribute(TextAttribute.FONT, sansSerifFont, 2, 5);
    as.addAttribute(TextAttribute.FOREGROUND, Color.red, 5, 6);
    as.addAttribute(TextAttribute.FOREGROUND, Color.red, 16, 17);

    g2.drawString(as.getIterator(), 40, 80);
}

From source file:GeneralPathOpenDemo2D.java

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

    g2.setPaint(Color.gray);//from www  .  j a  va2s.c o m
    int x = 5;
    int y = 7;

    // draw GeneralPath (polyline)

    int xPoints[] = { x, 200, x, 200 };
    int yPoints[] = { y, 200, 200, y };
    GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD, xPoints.length);
    polyline.moveTo(xPoints[0], yPoints[0]);
    for (int index = 1; index < xPoints.length; index++) {
        polyline.lineTo(xPoints[index], yPoints[index]);
    }

    g2.draw(polyline);
    g2.drawString("GeneralPath (open)", x, 250);
}