Example usage for java.awt Font getStringBounds

List of usage examples for java.awt Font getStringBounds

Introduction

In this page you can find the example usage for java.awt Font getStringBounds.

Prototype

public Rectangle2D getStringBounds(String str, FontRenderContext frc) 

Source Link

Document

Returns the logical bounds of the specified String in the specified FontRenderContext .

Usage

From source file:spinworld.gui.RadarPlot.java

/**
 * Draws the label for one axis.//w ww  .j a v a2 s  .  co  m
 *
 * @param g2  the graphics device.
 * @param plotArea  whole plot drawing area (e.g. including space for labels)
 * @param plotDrawingArea  the plot drawing area (just spanning of axis)
 * @param value  the value of the label (ignored).
 * @param cat  the category (zero-based index).
 * @param startAngle  the starting angle.
 * @param extent  the extent of the arc.
 */
protected void drawLabel(Graphics2D g2, Rectangle2D plotArea, Rectangle2D plotDrawingArea, double value,
        int cat, double startAngle, double extent) {
    FontRenderContext frc = g2.getFontRenderContext();

    String label = null;
    if (this.dataExtractOrder == TableOrder.BY_ROW) {
        // if series are in rows, then the categories are the column keys
        label = this.labelGenerator.generateColumnLabel(this.dataset, cat);
    } else {
        // if series are in columns, then the categories are the row keys
        label = this.labelGenerator.generateRowLabel(this.dataset, cat);
    }

    double angle = normalize(startAngle);

    Font font = getLabelFont();
    Point2D labelLocation;
    do {
        Rectangle2D labelBounds = font.getStringBounds(label, frc);
        LineMetrics lm = font.getLineMetrics(label, frc);
        double ascent = lm.getAscent();

        labelLocation = calculateLabelLocation(labelBounds, ascent, plotDrawingArea, startAngle);

        boolean leftOut = angle > 90 && angle < 270 && labelLocation.getX() < plotArea.getX();
        boolean rightOut = (angle < 90 || angle > 270)
                && labelLocation.getX() + labelBounds.getWidth() > plotArea.getX() + plotArea.getWidth();

        if (leftOut || rightOut) {
            font = font.deriveFont(font.getSize2D() - 1);
        } else {
            break;
        }
    } while (font.getSize() > 8);

    Composite saveComposite = g2.getComposite();

    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
    g2.setPaint(getLabelPaint());
    g2.setFont(font);
    g2.drawString(label, (float) labelLocation.getX(), (float) labelLocation.getY());
    g2.setComposite(saveComposite);
}

From source file:org.kalypsodeegree_impl.graphics.displayelements.LabelFactory.java

/**
 * Generates <tt>Label</tt> -representations for a given <tt>LabelDisplayElement</tt>.
 *///from   www.  j  a  va  2  s .  co  m
public Label[] createLabels() throws GM_Exception {
    try {
        final Feature feature = m_element.getFeature();

        final String caption = m_element.getLabel().evaluate(feature);
        // sanity check: empty labels are ignored
        if (StringUtils.isBlank(caption))
            return EMPTY_LABELS;

        // gather font information
        final org.kalypsodeegree.graphics.sld.Font sldFont = m_symbolizer.getFont();
        final java.awt.Font font = new java.awt.Font(sldFont.getFamily(feature),
                sldFont.getStyle(feature) | sldFont.getWeight(feature), sldFont.getSize(feature));
        m_graphics.setFont(font);

        final Color color = sldFont.getColor(feature);

        final FontRenderContext frc = m_graphics.getFontRenderContext();

        // bugstories...
        // I got the following error in the next line:
        // # An unexpected error has been detected by HotSpot Virtual Machine:
        // # [...]
        // # Problematic frame:
        // # C [libfontmanager.so+0x2ecd5]
        //
        // while running kalypso on linux, kubuntu-Dapper.
        // The error was caused by some buggy fonts in Dapper (Rekha-normal and aakar-MagNet ).
        // Work-around is to remove the toxic fonts by removing the package ttf-gujarati-fonts from the distribution.
        // this error was not easy to locate, so do not remove this notice !
        // ( v.doemming@tuhh.de )

        final Rectangle2D bounds = font.getStringBounds(caption, frc);
        final Dimension size = bounds.getBounds().getSize();
        final LineMetrics metrics = font.getLineMetrics(caption, frc);

        final GM_Object[] geometries = m_element.getGeometry();
        final List<Label> allLabels = new ArrayList<>();
        for (final GM_Object geometry : geometries) {
            final Label[] labels = createLabels(feature, caption, geometry, font, color, metrics, size);
            allLabels.addAll(Arrays.asList(labels));
        }

        return allLabels.toArray(new Label[allLabels.size()]);
    } catch (final FilterEvaluationException e) {
        // if properties are unknown to features, this should be ignored!
        return EMPTY_LABELS;
    }
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java

@Override
public void drawString(final String s, final float x, float y) {
    if (s.length() == 0) {
        return;/*from   w  ww.  j  av a  2 s.c om*/
    }
    setFillPaint();
    setStrokePaint();

    final AffineTransform at = getTransform();
    final AffineTransform at2 = getTransform();
    at2.translate(x, y);
    at2.concatenate(font.getTransform());
    setTransform(at2);
    final AffineTransform inverse = this.normalizeMatrix();
    final AffineTransform flipper = FLIP_TRANSFORM;
    inverse.concatenate(flipper);
    final double[] mx = new double[6];
    inverse.getMatrix(mx);
    cb.beginText();

    final float fontSize = font.getSize2D();
    if (lastBaseFont == null) {
        final String fontName = font.getName();
        final boolean bold = font.isBold();
        final boolean italic = font.isItalic();

        final BaseFontFontMetrics fontMetrics = metaData.getBaseFontFontMetrics(fontName, fontSize, bold,
                italic, null, metaData.isFeatureSupported(OutputProcessorFeature.EMBED_ALL_FONTS), false);
        final FontNativeContext nativeContext = fontMetrics.getNativeContext();
        lastBaseFont = fontMetrics.getBaseFont();

        cb.setFontAndSize(lastBaseFont, fontSize);
        if (fontMetrics.isTrueTypeFont() && bold && nativeContext.isNativeBold() == false) {
            final float strokeWidth = font.getSize2D() / 30.0f; // right from iText ...
            if (strokeWidth == 1) {
                cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
            } else {
                cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
                cb.setLineWidth(strokeWidth);
            }
        } else {
            cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
        }
    } else {
        cb.setFontAndSize(lastBaseFont, fontSize);
    }

    cb.setTextMatrix((float) mx[0], (float) mx[1], (float) mx[2], (float) mx[3], (float) mx[4], (float) mx[5]);
    double width = 0;
    if (fontSize > 0) {
        final float scale = 1000 / fontSize;
        final Font font = this.font.deriveFont(AffineTransform.getScaleInstance(scale, scale));
        final Rectangle2D stringBounds = font.getStringBounds(s, getFontRenderContext());
        width = stringBounds.getWidth() / scale;
    }
    if (s.length() > 1) {
        final float adv = ((float) width - lastBaseFont.getWidthPoint(s, fontSize)) / (s.length() - 1);
        cb.setCharacterSpacing(adv);
    }
    cb.showText(s);
    if (s.length() > 1) {
        cb.setCharacterSpacing(0);
    }
    cb.endText();
    setTransform(at);
    if (underline) {
        // These two are supposed to be taken from the .AFM file
        // int UnderlinePosition = -100;
        final int UnderlineThickness = 50;
        //
        final double d = PdfGraphics2D.asPoints(UnderlineThickness, (int) fontSize);
        setStroke(new BasicStroke((float) d));
        y = (float) ((y) + PdfGraphics2D.asPoints((UnderlineThickness), (int) fontSize));
        final Line2D line = new Line2D.Double(x, y, (width + x), y);
        draw(line);
    }
}

From source file:org.schemaspy.view.DotNode.java

private int getTextWidth(String text) {
    AffineTransform affinetransform = new AffineTransform();
    FontRenderContext frc = new FontRenderContext(affinetransform, true, true);
    int fontSize = Config.getInstance().getFontSize() + 1;
    Font font = new Font(Config.getInstance().getFont(), Font.BOLD, fontSize);
    int fontWidth = (int) (font.getStringBounds(text, frc).getWidth());
    return fontWidth;
}

From source file:pku.sei.checkedcoverage.jung.ShowJungGraph.java

public void displayGraph(DirectedGraph<VertexType, SliceEdge<VertexType>> graph) {
    JFrame mainFrame = new JFrame("slice graph display");
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Layout<VertexType, SliceEdge<VertexType>> layout = new KKLayout<VertexType, SliceEdge<VertexType>>(graph);
    final VisualizationViewer<VertexType, SliceEdge<VertexType>> viewer = new VisualizationViewer<VertexType, SliceEdge<VertexType>>(
            layout);// w  ww. j  a  v  a2  s  .  c om

    viewer.getRenderContext().setVertexLabelTransformer(this.vertexLabelTransformer);
    viewer.setVertexToolTipTransformer(this.vertexTooltipTransformer);
    viewer.getRenderContext().setEdgeLabelTransformer(new Transformer<SliceEdge<VertexType>, String>() {
        public String transform(SliceEdge<VertexType> edge) {
            Variable var = edge.getVariable();
            if (var instanceof ArrayElement) {
                ArrayElement elem = (ArrayElement) var;
                return "arr" + elem.getArrayId() + "[" + elem.getArrayIndex() + "]";
            } else if (var instanceof LocalVariable) {
                LocalVariable localVar = (LocalVariable) var;
                if (localVar.getVarName() != null)
                    return localVar.getVarName();
                return "local" + localVar.getVarIndex();
            } else if (var instanceof StackEntry) {
                return "stack";
            } else if (var instanceof ObjectField) {
                ObjectField objField = (ObjectField) var;
                return "obj" + objField.getObjectId() + "." + objField.getFieldName();
            } else if (var instanceof StaticField) {
                StaticField objField = (StaticField) var;
                String ownerInternalClassName = objField.getOwnerInternalClassName();
                String simpleClassName = getSimpleClassName(ownerInternalClassName);
                return simpleClassName + "." + objField.getFieldName();
            } else {
                assert var == null;
                return "";
            }
        }
    });
    viewer.setEdgeToolTipTransformer(new Transformer<SliceEdge<VertexType>, String>() {
        public String transform(SliceEdge<VertexType> edge) {
            Variable var = edge.getVariable();
            if (var instanceof ArrayElement) {
                ArrayElement elem = (ArrayElement) var;
                return "Array element " + elem.getArrayIndex() + " of array #" + elem.getArrayId();
            } else if (var instanceof LocalVariable) {
                LocalVariable localVar = (LocalVariable) var;
                if (localVar.getVarName() != null)
                    return "Local variable \"" + localVar.getVarName() + "\"";
                return "Local variable #" + localVar.getVarIndex();
            } else if (var instanceof StackEntry) {
                return "Dependency over the operand stack";
            } else if (var instanceof ObjectField) {
                ObjectField objField = (ObjectField) var;
                return "Field \"" + objField.getFieldName() + "\" of object #" + objField.getObjectId();
            } else if (var instanceof StaticField) {
                StaticField objField = (StaticField) var;
                String ownerInternalClassName = objField.getOwnerInternalClassName();
                return "Static field \"" + objField.getFieldName() + "\" of class \""
                        + Type.getType(ownerInternalClassName).getClassName();
            } else {
                assert var == null;
                return "Control dependency";
            }
        }
    });
    viewer.getRenderContext().setEdgeDrawPaintTransformer(new Transformer<SliceEdge<VertexType>, Paint>() {
        public Paint transform(SliceEdge<VertexType> edge) {
            return edge.getVariable() == null ? Color.red : Color.black;
        }
    });

    viewer.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);
    viewer.getRenderContext().setVertexShapeTransformer(new Transformer<VertexType, Shape>() {
        public Shape transform(VertexType inst) {
            Font font = viewer.getFont();
            String text = viewer.getRenderContext().getVertexLabelTransformer().transform(inst);
            FontRenderContext fontRenderContext = ((Graphics2D) viewer.getGraphics()).getFontRenderContext();
            Rectangle2D bounds = font.getStringBounds(text, fontRenderContext);
            return new RoundRectangle2D.Double(-.6 * bounds.getWidth(), -.6 * bounds.getHeight(),
                    1.2 * bounds.getWidth(), 1.2 * bounds.getHeight(), 8, 8);
        }
    });

    viewer.setBackground(Color.white);

    DefaultModalGraphMouse<InstructionInstance, SliceEdge<VertexType>> mouse = new DefaultModalGraphMouse<InstructionInstance, SliceEdge<VertexType>>();
    mouse.setMode(Mode.ANNOTATING);
    viewer.setGraphMouse(mouse);

    mainFrame.getContentPane().add(viewer);
    mainFrame.pack();

    mainFrame.setVisible(true);
}

From source file:savant.view.swing.GraphPane.java

/**
 * Render the background of this GraphPane
 *
 * @param g The graphics object to use/* w  w w . j a v a  2  s. c o  m*/
 */
private void renderBackground(Graphics2D g2, boolean xGridOn, boolean yGridOn) {
    int h = getHeight();
    int w = getWidth();

    // Paint a gradient from top to bottom
    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);
    g2.fillRect(0, 0, w, h);

    // We don't want the axes stomping on our labels, so make sure the clip excludes them.
    Area clipArea = new Area(new Rectangle(0, 0, w, h));
    Color gridColor = ColourSettings.getColor(ColourKey.AXIS_GRID);

    if (yGridOn) {
        // Smallish font for tick labels.
        Font tickFont = g2.getFont().deriveFont(Font.PLAIN, 9);

        int[] yTicks = MiscUtils.getTickPositions(transformYPixel(getHeight()), transformYPixel(0.0));

        g2.setColor(gridColor);
        g2.setFont(tickFont);
        for (int t : yTicks) {
            double y = transformYPos(t);

            // Skip labels at the top or bottom of the window because they look stupid.
            if (y != 0.0 && y != getHeight()) {
                String s = Integer.toString(t);
                Rectangle2D labelRect = tickFont.getStringBounds(s, g2.getFontRenderContext());
                double baseline = y + labelRect.getHeight() * 0.5 - 2.0;
                g2.drawString(s, 4.0F, (float) baseline);
                clipArea.subtract(new Area(new Rectangle2D.Double(3.0, baseline - labelRect.getHeight() - 1.0,
                        labelRect.getWidth() + 2.0, labelRect.getHeight() + 2.0)));
            }
        }
        g2.setClip(clipArea);
        for (int t2 : yTicks) {
            double y = transformYPos(t2);
            g2.draw(new Line2D.Double(0.0, y, w, y));
        }
    }
    if (xGridOn) {
        Range r = LocationController.getInstance().getRange();
        int[] xTicks = MiscUtils.getTickPositions(r);

        g2.setColor(gridColor);
        for (int t : xTicks) {
            double x = transformXPos(t);
            g2.draw(new Line2D.Double(x, 0, x, h));
        }
    }
    g2.setClip(null);
}

From source file:savant.view.swing.GraphPane.java

private void drawMessageHelper(Graphics2D g2, String message, Font font, int w, int h, int offset) {
    g2.setFont(font);/*from w ww .ja v a2  s  .  c  o m*/
    FontMetrics metrics = g2.getFontMetrics();

    Rectangle2D stringBounds = font.getStringBounds(message, g2.getFontRenderContext());

    int preferredWidth = (int) stringBounds.getWidth() + metrics.getHeight();
    int preferredHeight = (int) stringBounds.getHeight() + metrics.getHeight();

    w = Math.min(preferredWidth, w);
    h = Math.min(preferredHeight, h);

    int x = (getWidth() - (int) stringBounds.getWidth()) / 2;
    int y = (getHeight() / 2) + ((metrics.getAscent() - metrics.getDescent()) / 2) + offset;

    g2.drawString(message, x, y);
}