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:org.csml.tommo.sugar.modules.MappingQuality.java

protected void drawRowHeader(Graphics2D g2, final MappingQualityTableModel model, int imgSize, int width,
        int xOffset) {
    for (int r = 0; r < model.getRowCount(); r++) {
        int i = r / model.getTileNumeration().getCycleSize();
        String s = i < MappingQualityMatrix.THRESHOLDS.length ? "MAPQ<" + MappingQualityMatrix.THRESHOLDS[i]
                : "AVERAGE";

        if (model.getCycleID(r) == 0) {
            int stringHeight = g2.getFont().getSize(); //g2.getFontMetrics().getHeight();
            int stringWidth = g2.getFontMetrics().stringWidth(s);
            g2.drawString(s, 1 + width + (xOffset - 1 - stringWidth) / 2,
                    imgSize * (r + 1) - (imgSize - stringHeight) / 2);
        }/*from  ww w  .  jav  a 2  s .  c o m*/
    }
}

From source file:nl.b3p.imagetool.ImageTool.java

public static BufferedImage drawGeometries(BufferedImage bi, CombineImageSettings settings, int srid, Bbox bbox,
        int width, int height) throws Exception {
    List wktGeoms = settings.getWktGeoms();
    if (wktGeoms == null || wktGeoms.size() <= 0) {
        return bi;
    }/*from w ww.  j  a  va 2s .  co m*/
    BufferedImage newBufIm = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
    //        BufferedImage newBufIm = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D gbi = newBufIm.createGraphics();
    gbi.drawImage(bi, 0, 0, null);
    for (int i = 0; i < wktGeoms.size(); i++) {
        gbi.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
        CombineImageWkt ciw = (CombineImageWkt) wktGeoms.get(i);
        Color color = settings.getDefaultWktGeomColor();
        if (ciw.getColor() != null) {
            color = ciw.getColor();
        }
        gbi.setColor(color);
        String wktGeom = ciw.getWktGeom();
        Geometry geom = geometrieFromText(wktGeom, srid);
        Shape shape = createImage(geom, srid, bbox, width, height);
        Point centerPoint = null;
        if (geom instanceof Polygon) {
            gbi.fill(shape);
        } else if (geom instanceof com.vividsolutions.jts.geom.Point) {
            centerPoint = calculateCenter(shape, srid, bbox, width, height);
            gbi.draw(new Ellipse2D.Double(centerPoint.getX(), centerPoint.getY(), 4, 4));
        } else {
            gbi.setStroke(new BasicStroke(3));
            gbi.draw(shape);
        }
        if (ciw.getLabel() != null) {
            if (centerPoint == null) {
                centerPoint = calculateCenter(shape, srid, bbox, width, height);
            }
            gbi.setColor(Color.black);
            gbi.drawString(ciw.getLabel(), (float) centerPoint.getX(), (float) centerPoint.getY());
        }
    }
    gbi.dispose();
    return newBufIm;
}

From source file:org.squidy.designer.zoom.impl.VisualizationShape.java

/**
 * @param paintContext/*w  w w.  ja  v  a 2  s  . c  o  m*/
 */
protected void paintHeadline(PPaintContext paintContext) {

    Graphics2D g = paintContext.getGraphics();

    g.setFont(fontHeadline);
    FontMetrics fm = g.getFontMetrics();

    PBounds bounds = getBoundsReference();
    double x = bounds.getX();
    double width = bounds.getWidth();

    int titleWidth = FontUtils.getWidthOfText(fm, getTitle());
    g.drawString(getTitle(), (int) (x + width / 2) - (titleWidth / 2), 100);

    int breadcrumbWidth = FontUtils.getWidthOfText(fm, getBreadcrumb());
    g.drawString(getBreadcrumb(), (int) (x + width / 2) - (breadcrumbWidth / 2), 100 + fm.getHeight());
}

From source file:com.neophob.sematrix.core.generator.Textwriter.java

/**
 * create image.//from   w  w  w .ja va 2s  .c  o m
 *
 * @param text the text
 */
public void createTextImage(String text) {
    //only load if needed
    if (StringUtils.equals(text, this.text)) {
        return;
    }

    this.text = text;

    BufferedImage img = new BufferedImage(TEXT_BUFFER_X_SIZE, internalBufferYSize, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = img.createGraphics();
    FontRenderContext frc = g2.getFontRenderContext();
    TextLayout layout = new TextLayout(text, font, frc);
    Rectangle2D rect = layout.getBounds();

    int h = (int) (0.5f + rect.getHeight());
    //head and tailing space
    maxXPos = (int) (0.5f + rect.getWidth()) + 2 * internalBufferXSize;
    int ypos = internalBufferYSize - (internalBufferYSize - h) / 2;

    img = new BufferedImage(maxXPos, internalBufferYSize, BufferedImage.TYPE_BYTE_GRAY);
    g2 = img.createGraphics();

    g2.setColor(new Color(128));
    g2.setFont(font);
    g2.setClip(0, 0, maxXPos, internalBufferYSize);

    g2.drawString(text, internalBufferXSize, ypos);
    DataBufferByte dbi = (DataBufferByte) img.getRaster().getDataBuffer();
    byte[] textBuffer = dbi.getData();
    g2.dispose();

    xofs = 0;

    textAsImage = new int[maxXPos * internalBufferYSize];
    for (int i = 0; i < textAsImage.length; i++) {
        if (textBuffer[i] > 10) {
            textAsImage[i] = 127;
        } else {
            textAsImage[i] = 0;
        }
    }

    //clear internalbuffer
    Arrays.fill(this.internalBuffer, 0);
}

From source file:ca.sqlpower.wabit.report.ChartRenderer.java

public boolean renderReportContent(Graphics2D g, double width, double height, double scaleFactor, int pageIndex,
        boolean printing, SPVariableResolver variablesContext) {

    if (printing) {
        // If we're printing a streaming query, we have to
        // print whatever's displayed.
        if (this.chartCache == null || (this.chartCache != null && !this.chartCache.getQuery().isStreaming())) {
            refresh(false);/*  ww w  .  jav  a 2s  .co  m*/
        }
    } else if (needsRefresh || this.chartCache == null) {
        // No chart loaded. Doing a refresh will trigger a new 
        // redraw later on.
        refresh();
        return false;
    }

    JFreeChart jFreeChart = null;
    try {
        jFreeChart = ChartSwingUtil.createChartFromQuery(chartCache);
        if (jFreeChart == null) {
            g.drawString("Loading...", 0, g.getFontMetrics().getHeight());
            return false;
        }

        Rectangle2D area = new Rectangle2D.Double(0, 0, width, height);

        // first pass establishes rendering info but draws nothing
        ChartRenderingInfo info = new ChartRenderingInfo();
        Graphics2D dummyGraphics = (Graphics2D) g.create(0, 0, 0, 0);
        jFreeChart.draw(dummyGraphics, area, info);
        dummyGraphics.dispose();

        // now for real
        Rectangle2D plotArea = info.getPlotInfo().getDataArea();
        ChartGradientPainter.paintChartGradient(g, area, (int) plotArea.getMaxY());
        jFreeChart.draw(g, area);

    } catch (Exception e) {
        logger.error("Error while rendering chart", e);
        g.drawString("Could not render chart: " + e.getMessage(), 0, g.getFontMetrics().getHeight());
    }
    return false;
}

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

/**Render default view if there is no timeframe yet*/
private void renderNoInfoView(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setPaint(new TexturePaint(STROKED, new Rectangle(0, 0, 3, 3)));
    g2d.fillRect(0, 0, getWidth(), getHeight());
    Font f = g2d.getFont().deriveFont(Font.BOLD, 14.0f);
    g2d.setFont(f);//from  w w w  .  j a va  2  s . c o  m
    Rectangle2D bounds = g2d.getFontMetrics().getStringBounds("Kein Zeitfenster aktiv", g);
    int dx = 10;
    if (getWidth() > bounds.getWidth()) {
        dx = (int) Math.rint((getWidth() - bounds.getWidth()) / 2);
    }

    int dy = 10;
    if (getHeight() > bounds.getHeight()) {
        dy = (int) Math.rint((getHeight() - bounds.getHeight()) / 2);
    }
    g2d.setColor(Color.black);
    g2d.drawString("Kein Zeitfenster aktiv", dx, dy);
}

From source file:org.squidy.designer.model.NodeShape.java

@Override
protected void paintShapeZoomedIn(PPaintContext paintContext) {
    super.paintShapeZoomedIn(paintContext);

    Graphics2D g = paintContext.getGraphics();

    PBounds bounds = getBoundsReference();
    int x = (int) bounds.getX();
    int y = (int) bounds.getY();

    g.setFont(fontProperties);/*w w  w .  j  a  va 2 s.  c om*/
    g.drawString("Properties", x + 50, y + 300);
}

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

/**
 * Simplest kind of legend is just a list of coloured lines with names next to them.
 *///from  w ww.  j a v a 2s.  c om
protected void drawSimpleLegend(Graphics2D g2, int x, int y, ColourKey... keys) {
    ColourScheme cs = (ColourScheme) instructions.get(DrawingInstruction.COLOUR_SCHEME);

    g2.setFont(LEGEND_FONT);

    for (ColourKey k : keys) {
        String legendString = k.getName();
        g2.setColor(cs.getColor(k));
        g2.setStroke(TWO_STROKE);
        Rectangle2D stringRect = LEGEND_FONT.getStringBounds(legendString, g2.getFontRenderContext());
        g2.drawLine(x - 25, y - (int) stringRect.getHeight() / 2, x - 5, y - (int) stringRect.getHeight() / 2);
        g2.setColor(cs.getColor(ColourKey.INTERVAL_LINE));
        g2.setStroke(ONE_STROKE);
        g2.drawString(legendString, x, y);

        y += LEGEND_LINE_HEIGHT;
    }
}

From source file:org.springframework.cloud.stream.app.image.recognition.processor.ImageRecognitionOutputMessageBuilder.java

/**
 * Augment the input image by adding the recognized classes.
 *
 * @param imageBytes input image as byte array
 * @param result computed recognition labels
 * @return the image augmented with recognized labels.
 *///w w w. j  a v  a 2 s.  com
private byte[] drawLabels(byte[] imageBytes, Object result) {
    try {
        if (result != null) {
            BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageBytes));

            Graphics2D g = originalImage.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            FontMetrics fm = g.getFontMetrics();

            Tuple resultTuple = new JsonStringToTupleConverter().convert(result.toString());
            ArrayList<Tuple> labels = (ArrayList) resultTuple.getValues().get(0);

            int x = 1;
            int y = 1;
            for (Tuple l : labels) {

                String labelName = l.getFieldNames().get(0);
                int probability = (int) (100 * l.getFloat(0));
                String title = labelName + ": " + probability + "%";

                Rectangle2D rect = fm.getStringBounds(title, g);

                g.setColor(bgColor);
                g.fillRect(x, y, (int) rect.getWidth() + 6, (int) rect.getHeight());

                g.setColor(textColor);
                g.drawString(title, x + 3, (int) (y + rect.getHeight() - 3));
                y = (int) (y + rect.getHeight() + 1);
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(originalImage, IMAGE_FORMAT, baos);
            baos.flush();
            imageBytes = baos.toByteArray();
            baos.close();
        }
    } catch (IOException e) {
        logger.error("Failed to draw labels in the input image", e);
    }

    return imageBytes;
}

From source file:swift.selenium.WebHelper.java

/**
 * This function embosses the message on the screenshot
 * @param imageFilePath//from   ww  w. ja va  2 s  . c o  m
 * @param text
 * @param textPosition
 * @return
 * @throws IOException
 */
public static byte[] mergeImageAndText(String imageFilePath, String text, Point textPosition)
        throws IOException {
    BufferedImage im = ImageIO.read(new File(imageFilePath));
    Graphics2D g2 = im.createGraphics();
    g2.setColor(Color.RED);
    g2.setBackground(Color.WHITE);
    g2.drawString(text, textPosition.x, textPosition.y);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(im, "PNG", baos);
    return baos.toByteArray();
}