Java Code Examples for java.awt.Font#getLineMetrics()

The following examples show how to use java.awt.Font#getLineMetrics() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MarkerAxisBand.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * A utility method that draws a string inside a rectangle.
 *
 * @param g2  the graphics device.
 * @param bounds  the rectangle.
 * @param font  the font.
 * @param text  the text.
 */
private void drawStringInRect(Graphics2D g2, Rectangle2D bounds, Font font,
                              String text) {

    g2.setFont(font);
    FontMetrics fm = g2.getFontMetrics(font);
    Rectangle2D r = TextUtilities.getTextBounds(text, g2, fm);
    double x = bounds.getX();
    if (r.getWidth() < bounds.getWidth()) {
        x = x + (bounds.getWidth() - r.getWidth()) / 2;
    }
    LineMetrics metrics = font.getLineMetrics(
        text, g2.getFontRenderContext()
    );
    g2.drawString(
        text, (float) x, (float) (bounds.getMaxY()
            - this.bottomInnerGap - metrics.getDescent())
    );
}
 
Example 2
Source File: TextLayout.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
private void fastInit(char[] chars, Font font,
                      Map<? extends Attribute, ?> attrs,
                      FontRenderContext frc) {

    // Object vf = attrs.get(TextAttribute.ORIENTATION);
    // isVerticalLine = TextAttribute.ORIENTATION_VERTICAL.equals(vf);
    isVerticalLine = false;

    LineMetrics lm = font.getLineMetrics(chars, 0, chars.length, frc);
    CoreMetrics cm = CoreMetrics.get(lm);
    byte glyphBaseline = (byte) cm.baselineIndex;

    if (attrs == null) {
        baseline = glyphBaseline;
        baselineOffsets = cm.baselineOffsets;
        justifyRatio = 1.0f;
    } else {
        paragraphInit(glyphBaseline, cm, attrs, chars);
    }

    characterCount = chars.length;

    textLine = TextLine.fastCreateTextLine(frc, chars, font, cm, attrs);
}
 
Example 3
Source File: TextLayout.java    From Java8CN with Apache License 2.0 6 votes vote down vote up
private void fastInit(char[] chars, Font font,
                      Map<? extends Attribute, ?> attrs,
                      FontRenderContext frc) {

    // Object vf = attrs.get(TextAttribute.ORIENTATION);
    // isVerticalLine = TextAttribute.ORIENTATION_VERTICAL.equals(vf);
    isVerticalLine = false;

    LineMetrics lm = font.getLineMetrics(chars, 0, chars.length, frc);
    CoreMetrics cm = CoreMetrics.get(lm);
    byte glyphBaseline = (byte) cm.baselineIndex;

    if (attrs == null) {
        baseline = glyphBaseline;
        baselineOffsets = cm.baselineOffsets;
        justifyRatio = 1.0f;
    } else {
        paragraphInit(glyphBaseline, cm, attrs, chars);
    }

    characterCount = chars.length;

    textLine = TextLine.fastCreateTextLine(frc, chars, font, cm, attrs);
}
 
Example 4
Source File: TextLayout.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
private void fastInit(char[] chars, Font font,
                      Map<? extends Attribute, ?> attrs,
                      FontRenderContext frc) {

    // Object vf = attrs.get(TextAttribute.ORIENTATION);
    // isVerticalLine = TextAttribute.ORIENTATION_VERTICAL.equals(vf);
    isVerticalLine = false;

    LineMetrics lm = font.getLineMetrics(chars, 0, chars.length, frc);
    CoreMetrics cm = CoreMetrics.get(lm);
    byte glyphBaseline = (byte) cm.baselineIndex;

    if (attrs == null) {
        baseline = glyphBaseline;
        baselineOffsets = cm.baselineOffsets;
        justifyRatio = 1.0f;
    } else {
        paragraphInit(glyphBaseline, cm, attrs, chars);
    }

    characterCount = chars.length;

    textLine = TextLine.fastCreateTextLine(frc, chars, font, cm, attrs);
}
 
Example 5
Source File: TextLayout.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private void fastInit(char[] chars, Font font,
                      Map<? extends Attribute, ?> attrs,
                      FontRenderContext frc) {

    // Object vf = attrs.get(TextAttribute.ORIENTATION);
    // isVerticalLine = TextAttribute.ORIENTATION_VERTICAL.equals(vf);
    isVerticalLine = false;

    LineMetrics lm = font.getLineMetrics(chars, 0, chars.length, frc);
    CoreMetrics cm = CoreMetrics.get(lm);
    byte glyphBaseline = (byte) cm.baselineIndex;

    if (attrs == null) {
        baseline = glyphBaseline;
        baselineOffsets = cm.baselineOffsets;
        justifyRatio = 1.0f;
    } else {
        paragraphInit(glyphBaseline, cm, attrs, chars);
    }

    characterCount = chars.length;

    textLine = TextLine.fastCreateTextLine(frc, chars, font, cm, attrs);
}
 
Example 6
Source File: TextLayout.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
private void fastInit(char[] chars, Font font,
                      Map<? extends Attribute, ?> attrs,
                      FontRenderContext frc) {

    // Object vf = attrs.get(TextAttribute.ORIENTATION);
    // isVerticalLine = TextAttribute.ORIENTATION_VERTICAL.equals(vf);
    isVerticalLine = false;

    LineMetrics lm = font.getLineMetrics(chars, 0, chars.length, frc);
    CoreMetrics cm = CoreMetrics.get(lm);
    byte glyphBaseline = (byte) cm.baselineIndex;

    if (attrs == null) {
        baseline = glyphBaseline;
        baselineOffsets = cm.baselineOffsets;
        justifyRatio = 1.0f;
    } else {
        paragraphInit(glyphBaseline, cm, attrs, chars);
    }

    characterCount = chars.length;

    textLine = TextLine.fastCreateTextLine(frc, chars, font, cm, attrs);
}
 
Example 7
Source File: ValueAxis.java    From SIMVA-SoS with Apache License 2.0 5 votes vote down vote up
/**
 * A utility method for determining the width of the widest tick label.
 *
 * @param ticks  the ticks.
 * @param g2  the graphics device.
 * @param drawArea  the area within which the plot and axes should be drawn.
 * @param vertical  a flag that indicates whether or not the tick labels
 *                  are 'vertical'.
 *
 * @return The width of the tallest tick label.
 */
protected double findMaximumTickLabelWidth(List ticks, Graphics2D g2,
        Rectangle2D drawArea, boolean vertical) {

    RectangleInsets insets = getTickLabelInsets();
    Font font = getTickLabelFont();
    double maxWidth = 0.0;
    if (!vertical) {
        FontMetrics fm = g2.getFontMetrics(font);
        Iterator iterator = ticks.iterator();
        while (iterator.hasNext()) {
            Tick tick = (Tick) iterator.next();
            Rectangle2D labelBounds = null;
            if (tick instanceof LogTick) {
                LogTick lt = (LogTick) tick;
                if (lt.getAttributedLabel() != null) {
                    labelBounds = AttrStringUtils.getTextBounds(
                            lt.getAttributedLabel(), g2);
                }
            } else if (tick.getText() != null) {
                labelBounds = TextUtilities.getTextBounds(tick.getText(), 
                        g2, fm);
            }
            if (labelBounds != null 
                    && labelBounds.getWidth() + insets.getLeft()
                    + insets.getRight() > maxWidth) {
                maxWidth = labelBounds.getWidth()
                           + insets.getLeft() + insets.getRight();
            }
        }
    } else {
        LineMetrics metrics = font.getLineMetrics("ABCxyz",
                g2.getFontRenderContext());
        maxWidth = metrics.getHeight()
                   + insets.getTop() + insets.getBottom();
    }
    return maxWidth;

}
 
Example 8
Source File: DateAxis.java    From buffer_bci with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Estimates the maximum width of the tick labels, assuming the specified
 * tick unit is used.
 * <P>
 * Rather than computing the string bounds of every tick on the axis, we
 * just look at two values: the lower bound and the upper bound for the
 * axis.  These two values will usually be representative.
 *
 * @param g2  the graphics device.
 * @param unit  the tick unit to use for calculation.
 *
 * @return The estimated maximum width of the tick labels.
 */
private double estimateMaximumTickLabelWidth(Graphics2D g2, 
        DateTickUnit unit) {

    RectangleInsets tickLabelInsets = getTickLabelInsets();
    double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();

    Font tickLabelFont = getTickLabelFont();
    FontRenderContext frc = g2.getFontRenderContext();
    LineMetrics lm = tickLabelFont.getLineMetrics("ABCxyz", frc);
    if (isVerticalTickLabels()) {
        // all tick labels have the same width (equal to the height of
        // the font)...
        result += lm.getHeight();
    }
    else {
        // look at lower and upper bounds...
        DateRange range = (DateRange) getRange();
        Date lower = range.getLowerDate();
        Date upper = range.getUpperDate();
        String lowerStr, upperStr;
        DateFormat formatter = getDateFormatOverride();
        if (formatter != null) {
            lowerStr = formatter.format(lower);
            upperStr = formatter.format(upper);
        }
        else {
            lowerStr = unit.dateToString(lower);
            upperStr = unit.dateToString(upper);
        }
        FontMetrics fm = g2.getFontMetrics(tickLabelFont);
        double w1 = fm.stringWidth(lowerStr);
        double w2 = fm.stringWidth(upperStr);
        result += Math.max(w1, w2);
    }

    return result;

}
 
Example 9
Source File: DateAxis.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Estimates the maximum width of the tick labels, assuming the specified 
 * tick unit is used.
 * <P>
 * Rather than computing the string bounds of every tick on the axis, we
 * just look at two values: the lower bound and the upper bound for the 
 * axis.  These two values will usually be representative.
 *
 * @param g2  the graphics device.
 * @param unit  the tick unit to use for calculation.
 *
 * @return The estimated maximum width of the tick labels.
 */
private double estimateMaximumTickLabelWidth(Graphics2D g2, 
                                             DateTickUnit unit) {

    RectangleInsets tickLabelInsets = getTickLabelInsets();
    double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();

    Font tickLabelFont = getTickLabelFont();
    FontRenderContext frc = g2.getFontRenderContext();
    LineMetrics lm = tickLabelFont.getLineMetrics("ABCxyz", frc);
    if (isVerticalTickLabels()) {
        // all tick labels have the same width (equal to the height of 
        // the font)...
        result += lm.getHeight();
    }
    else {
        // look at lower and upper bounds...
        DateRange range = (DateRange) getRange();
        Date lower = range.getLowerDate();
        Date upper = range.getUpperDate();
        String lowerStr = null;
        String upperStr = null;
        DateFormat formatter = getDateFormatOverride();
        if (formatter != null) {
            lowerStr = formatter.format(lower);
            upperStr = formatter.format(upper);
        }
        else {
            lowerStr = unit.dateToString(lower);
            upperStr = unit.dateToString(upper);
        }
        FontMetrics fm = g2.getFontMetrics(tickLabelFont);
        double w1 = fm.stringWidth(lowerStr);
        double w2 = fm.stringWidth(upperStr);
        result += Math.max(w1, w2);
    }

    return result;

}
 
Example 10
Source File: ValueAxis.java    From ccu-historian with GNU General Public License v3.0 5 votes vote down vote up
/**
 * A utility method for determining the width of the widest tick label.
 *
 * @param ticks  the ticks.
 * @param g2  the graphics device.
 * @param drawArea  the area within which the plot and axes should be drawn.
 * @param vertical  a flag that indicates whether or not the tick labels
 *                  are 'vertical'.
 *
 * @return The width of the tallest tick label.
 */
protected double findMaximumTickLabelWidth(List ticks, Graphics2D g2,
        Rectangle2D drawArea, boolean vertical) {

    RectangleInsets insets = getTickLabelInsets();
    Font font = getTickLabelFont();
    double maxWidth = 0.0;
    if (!vertical) {
        FontMetrics fm = g2.getFontMetrics(font);
        Iterator iterator = ticks.iterator();
        while (iterator.hasNext()) {
            Tick tick = (Tick) iterator.next();
            Rectangle2D labelBounds = null;
            if (tick instanceof LogTick) {
                LogTick lt = (LogTick) tick;
                if (lt.getAttributedLabel() != null) {
                    labelBounds = AttrStringUtils.getTextBounds(
                            lt.getAttributedLabel(), g2);
                }
            } else if (tick.getText() != null) {
                labelBounds = TextUtilities.getTextBounds(tick.getText(), 
                        g2, fm);
            }
            if (labelBounds != null 
                    && labelBounds.getWidth() + insets.getLeft()
                    + insets.getRight() > maxWidth) {
                maxWidth = labelBounds.getWidth()
                           + insets.getLeft() + insets.getRight();
            }
        }
    } else {
        LineMetrics metrics = font.getLineMetrics("ABCxyz",
                g2.getFontRenderContext());
        maxWidth = metrics.getHeight()
                   + insets.getTop() + insets.getBottom();
    }
    return maxWidth;

}
 
Example 11
Source File: FontDisposeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception
{
    // The bug only happens with Type 1 fonts. The Ghostscript font files
    // should be commonly available. From distro pacakge or
    //  ftp://ftp.gnu.org/gnu/ghostscript/gnu-gs-fonts-other-6.0.tar.gz
    // Pass pfa/pfb font file as argument
    String path = args[0];

    // Load
    InputStream stream = new FileInputStream(path);
    Font font = Font.createFont(Font.TYPE1_FONT,stream);

    // Ensure native bits have been generated
    BufferedImage img = new BufferedImage(100,100,
                             BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = img.createGraphics();
    FontRenderContext frc = g2d.getFontRenderContext();

    font.getLineMetrics("derp",frc);

    // Force disposal -
    // System.gc() is not sufficient.
    Field font2DHandleField = Font.class.getDeclaredField("font2DHandle");
    font2DHandleField.setAccessible(true);
    sun.font.Font2DHandle font2DHandle =
                  (sun.font.Font2DHandle)font2DHandleField.get(font);

    sun.font.Font2D font2D = font2DHandle.font2D;
    sun.font.Type1Font type1Font = (sun.font.Type1Font)font2D;

    Method getScalerMethod =
    sun.font.Type1Font.class.getDeclaredMethod("getScaler");
    getScalerMethod.setAccessible(true);
    sun.font.FontScaler scaler =
              (sun.font.FontScaler)getScalerMethod.invoke(type1Font);

    // dispose should not crash due to double free
    scaler.dispose();
}
 
Example 12
Source File: TextLine.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns an array in logical order of the TextLineComponents on
 * the text in the given range, with the given attributes.
 */
public static TextLineComponent[] createComponentsOnRun(int runStart,
                                                        int runLimit,
                                                        char[] chars,
                                                        int[] charsLtoV,
                                                        byte[] levels,
                                                        TextLabelFactory factory,
                                                        Font font,
                                                        CoreMetrics cm,
                                                        FontRenderContext frc,
                                                        Decoration decorator,
                                                        TextLineComponent[] components,
                                                        int numComponents) {

    int pos = runStart;
    do {
        int chunkLimit = firstVisualChunk(charsLtoV, levels, pos, runLimit); // <= displayLimit

        do {
            int startPos = pos;
            int lmCount;

            if (cm == null) {
                LineMetrics lineMetrics = font.getLineMetrics(chars, startPos, chunkLimit, frc);
                cm = CoreMetrics.get(lineMetrics);
                lmCount = lineMetrics.getNumChars();
            }
            else {
                lmCount = (chunkLimit-startPos);
            }

            TextLineComponent nextComponent =
                factory.createExtended(font, cm, decorator, startPos, startPos + lmCount);

            ++numComponents;
            if (numComponents >= components.length) {
                components = expandArray(components);
            }

            components[numComponents-1] = nextComponent;

            pos += lmCount;
        } while (pos < chunkLimit);

    } while (pos < runLimit);

    return components;
}
 
Example 13
Source File: TextLine.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns an array in logical order of the TextLineComponents on
 * the text in the given range, with the given attributes.
 */
public static TextLineComponent[] createComponentsOnRun(int runStart,
                                                        int runLimit,
                                                        char[] chars,
                                                        int[] charsLtoV,
                                                        byte[] levels,
                                                        TextLabelFactory factory,
                                                        Font font,
                                                        CoreMetrics cm,
                                                        FontRenderContext frc,
                                                        Decoration decorator,
                                                        TextLineComponent[] components,
                                                        int numComponents) {

    int pos = runStart;
    do {
        int chunkLimit = firstVisualChunk(charsLtoV, levels, pos, runLimit); // <= displayLimit

        do {
            int startPos = pos;
            int lmCount;

            if (cm == null) {
                LineMetrics lineMetrics = font.getLineMetrics(chars, startPos, chunkLimit, frc);
                cm = CoreMetrics.get(lineMetrics);
                lmCount = lineMetrics.getNumChars();
            }
            else {
                lmCount = (chunkLimit-startPos);
            }

            TextLineComponent nextComponent =
                factory.createExtended(font, cm, decorator, startPos, startPos + lmCount);

            ++numComponents;
            if (numComponents >= components.length) {
                components = expandArray(components);
            }

            components[numComponents-1] = nextComponent;

            pos += lmCount;
        } while (pos < chunkLimit);

    } while (pos < runLimit);

    return components;
}
 
Example 14
Source File: SimpleTextLineWrapper.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected float determineLeading(Font font)
{
	LineMetrics lineMetrics = font.getLineMetrics(" ", context.getFontRenderContext());
	return lineMetrics.getLeading();
}
 
Example 15
Source File: StandardTextSource.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
   * Create a simple implementation of a TextSource.
   *
   * Chars is an array containing clen chars in the context, in
   * logical order, contiguously starting at cstart.  Start and len
   * represent that portion of the context representing the true
   * source; start, like cstart, is relative to the start of the
   * character array.
   *
   * Level is the bidi level (0-63 for the entire context. Flags is
   * the layout flags. Font is the font, frc is the render context,
   * and lm is the line metrics for the entire source text, but not
   * necessarily the context.
   */
  StandardTextSource(char[] chars,
                     int start,
                     int len,
                     int cstart,
                     int clen,
                     int level,
                     int flags,
                     Font font,
                     FontRenderContext frc,
                     CoreMetrics cm) {
  if (chars == null) {
    throw new IllegalArgumentException("bad chars: null");
  }
  if (cstart < 0) {
    throw new IllegalArgumentException("bad cstart: " + cstart);
  }
  if (start < cstart) {
    throw new IllegalArgumentException("bad start: " + start + " for cstart: " + cstart);
  }
  if (clen < 0) {
    throw new IllegalArgumentException("bad clen: " + clen);
  }
  if (cstart + clen > chars.length) {
    throw new IllegalArgumentException("bad clen: " + clen + " cstart: " + cstart + " for array len: " + chars.length);
  }
  if (len < 0) {
    throw new IllegalArgumentException("bad len: " + len);
  }
  if ((start + len) > (cstart + clen)) {
    throw new IllegalArgumentException("bad len: " + len + " start: " + start + " for cstart: " + cstart + " clen: " + clen);
  }
  if (font == null) {
    throw new IllegalArgumentException("bad font: null");
  }
  if (frc == null) {
    throw new IllegalArgumentException("bad frc: null");
  }

  this.chars = chars;
  this.start = start;
  this.len = len;
  this.cstart = cstart;
  this.clen = clen;
  this.level = level;
  this.flags = flags;
  this.font = font;
  this.frc = frc;

  if (cm != null) {
      this.cm = cm;
  } else {
      LineMetrics metrics = font.getLineMetrics(chars, cstart, clen, frc);
      this.cm = ((FontLineMetrics)metrics).cm;
  }
}
 
Example 16
Source File: TextLine.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns an array in logical order of the TextLineComponents on
 * the text in the given range, with the given attributes.
 */
public static TextLineComponent[] createComponentsOnRun(int runStart,
                                                        int runLimit,
                                                        char[] chars,
                                                        int[] charsLtoV,
                                                        byte[] levels,
                                                        TextLabelFactory factory,
                                                        Font font,
                                                        CoreMetrics cm,
                                                        FontRenderContext frc,
                                                        Decoration decorator,
                                                        TextLineComponent[] components,
                                                        int numComponents) {

    int pos = runStart;
    do {
        int chunkLimit = firstVisualChunk(charsLtoV, levels, pos, runLimit); // <= displayLimit

        do {
            int startPos = pos;
            int lmCount;

            if (cm == null) {
                LineMetrics lineMetrics = font.getLineMetrics(chars, startPos, chunkLimit, frc);
                cm = CoreMetrics.get(lineMetrics);
                lmCount = lineMetrics.getNumChars();
            }
            else {
                lmCount = (chunkLimit-startPos);
            }

            TextLineComponent nextComponent =
                factory.createExtended(font, cm, decorator, startPos, startPos + lmCount);

            ++numComponents;
            if (numComponents >= components.length) {
                components = expandArray(components);
            }

            components[numComponents-1] = nextComponent;

            pos += lmCount;
        } while (pos < chunkLimit);

    } while (pos < runLimit);

    return components;
}
 
Example 17
Source File: TextUtilities.java    From ccu-historian with GNU General Public License v3.0 4 votes vote down vote up
/**
 * A utility method that calculates the anchor offsets for a string.
 * Normally, the (x, y) coordinate for drawing text is a point on the
 * baseline at the left of the text string.  If you add these offsets to
 * (x, y) and draw the string, then the anchor point should coincide with
 * the (x, y) point.
 *
 * @param g2  the graphics device (not <code>null</code>).
 * @param text  the text.
 * @param anchor  the anchor point.
 * @param textBounds  the text bounds (if not <code>null</code>, this
 *                    object will be updated by this method to match the
 *                    string bounds).
 *
 * @return  The offsets.
 */
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
        String text, TextAnchor anchor, Rectangle2D textBounds) {

    float[] result = new float[3];
    FontRenderContext frc = g2.getFontRenderContext();
    Font f = g2.getFont();
    FontMetrics fm = g2.getFontMetrics(f);
    Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
    LineMetrics metrics = f.getLineMetrics(text, frc);
    float ascent = metrics.getAscent();
    result[2] = -ascent;
    float halfAscent = ascent / 2.0f;
    float descent = metrics.getDescent();
    float leading = metrics.getLeading();
    float xAdj = 0.0f;
    float yAdj = 0.0f;

    if (anchor.isHorizontalCenter()) {
        xAdj = (float) -bounds.getWidth() / 2.0f;
    }
    else if (anchor.isRight()) {
        xAdj = (float) -bounds.getWidth();
    }

    if (anchor.isTop()) {
        yAdj = -descent - leading + (float) bounds.getHeight();
    }
    else if (anchor.isHalfAscent()) {
        yAdj = halfAscent;
    }
    else if (anchor.isVerticalCenter()) {
        yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
    }
    else if (anchor.isBaseline()) {
        yAdj = 0.0f;
    }
    else if (anchor.isBottom()) {
        yAdj = -metrics.getDescent() - metrics.getLeading();
    }
    if (textBounds != null) {
        textBounds.setRect(bounds);
    }
    result[0] = xAdj;
    result[1] = yAdj;
    return result;

}
 
Example 18
Source File: TextUtils.java    From openstock with GNU General Public License v3.0 4 votes vote down vote up
/**
 * A utility method that calculates the anchor offsets for a string.
 * Normally, the (x, y) coordinate for drawing text is a point on the
 * baseline at the left of the text string.  If you add these offsets to
 * (x, y) and draw the string, then the anchor point should coincide with
 * the (x, y) point.
 *
 * @param g2  the graphics device (not <code>null</code>).
 * @param text  the text.
 * @param anchor  the anchor point.
 *
 * @return  The offsets.
 */
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
        String text, TextAnchor anchor) {

    float[] result = new float[2];
    FontRenderContext frc = g2.getFontRenderContext();
    Font f = g2.getFont();
    FontMetrics fm = g2.getFontMetrics(f);
    Rectangle2D bounds = getTextBounds(text, fm);
    LineMetrics metrics = f.getLineMetrics(text, frc);
    float ascent = metrics.getAscent();
    float halfAscent = ascent / 2.0f;
    float descent = metrics.getDescent();
    float leading = metrics.getLeading();
    float xAdj = 0.0f;
    float yAdj = 0.0f;

    if (anchor.isHorizontalCenter()) {
        xAdj = (float) -bounds.getWidth() / 2.0f;
    }
    else if (anchor.isRight()) {
        xAdj = (float) -bounds.getWidth();
    }

    if (anchor.isTop()) {
        yAdj = -descent - leading + (float) bounds.getHeight();
    }
    else if (anchor.isHalfAscent()) {
        yAdj = halfAscent;
    }
    else if (anchor.isVerticalCenter()) {
        yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
    }
    else if (anchor.isBaseline()) {
        yAdj = 0.0f;
    }
    else if (anchor.isBottom()) {
        yAdj = -metrics.getDescent() - metrics.getLeading();
    }
    result[0] = xAdj;
    result[1] = yAdj;
    return result;

}
 
Example 19
Source File: StandardTextSource.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
   * Create a simple implementation of a TextSource.
   *
   * Chars is an array containing clen chars in the context, in
   * logical order, contiguously starting at cstart.  Start and len
   * represent that portion of the context representing the true
   * source; start, like cstart, is relative to the start of the
   * character array.
   *
   * Level is the bidi level (0-63 for the entire context. Flags is
   * the layout flags. Font is the font, frc is the render context,
   * and lm is the line metrics for the entire source text, but not
   * necessarily the context.
   */
  StandardTextSource(char[] chars,
                     int start,
                     int len,
                     int cstart,
                     int clen,
                     int level,
                     int flags,
                     Font font,
                     FontRenderContext frc,
                     CoreMetrics cm) {
  if (chars == null) {
    throw new IllegalArgumentException("bad chars: null");
  }
  if (cstart < 0) {
    throw new IllegalArgumentException("bad cstart: " + cstart);
  }
  if (start < cstart) {
    throw new IllegalArgumentException("bad start: " + start + " for cstart: " + cstart);
  }
  if (clen < 0) {
    throw new IllegalArgumentException("bad clen: " + clen);
  }
  if (cstart + clen > chars.length) {
    throw new IllegalArgumentException("bad clen: " + clen + " cstart: " + cstart + " for array len: " + chars.length);
  }
  if (len < 0) {
    throw new IllegalArgumentException("bad len: " + len);
  }
  if ((start + len) > (cstart + clen)) {
    throw new IllegalArgumentException("bad len: " + len + " start: " + start + " for cstart: " + cstart + " clen: " + clen);
  }
  if (font == null) {
    throw new IllegalArgumentException("bad font: null");
  }
  if (frc == null) {
    throw new IllegalArgumentException("bad frc: null");
  }

  this.chars = chars;
  this.start = start;
  this.len = len;
  this.cstart = cstart;
  this.clen = clen;
  this.level = level;
  this.flags = flags;
  this.font = font;
  this.frc = frc;

  if (cm != null) {
      this.cm = cm;
  } else {
      LineMetrics metrics = font.getLineMetrics(chars, cstart, clen, frc);
      this.cm = ((FontLineMetrics)metrics).cm;
  }
}
 
Example 20
Source File: TextUtilities.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * A utility method that calculates the anchor offsets for a string.
 * Normally, the (x, y) coordinate for drawing text is a point on the
 * baseline at the left of the text string.  If you add these offsets to
 * (x, y) and draw the string, then the anchor point should coincide with
 * the (x, y) point.
 *
 * @param g2  the graphics device (not <code>null</code>).
 * @param text  the text.
 * @param anchor  the anchor point.
 * @param textBounds  the text bounds (if not <code>null</code>, this
 *                    object will be updated by this method to match the
 *                    string bounds).
 *
 * @return  The offsets.
 */
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
        String text, TextAnchor anchor, Rectangle2D textBounds) {

    float[] result = new float[3];
    FontRenderContext frc = g2.getFontRenderContext();
    Font f = g2.getFont();
    FontMetrics fm = g2.getFontMetrics(f);
    Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
    LineMetrics metrics = f.getLineMetrics(text, frc);
    float ascent = metrics.getAscent();
    result[2] = -ascent;
    float halfAscent = ascent / 2.0f;
    float descent = metrics.getDescent();
    float leading = metrics.getLeading();
    float xAdj = 0.0f;
    float yAdj = 0.0f;

    if (anchor == TextAnchor.TOP_CENTER
            || anchor == TextAnchor.CENTER
            || anchor == TextAnchor.BOTTOM_CENTER
            || anchor == TextAnchor.BASELINE_CENTER
            || anchor == TextAnchor.HALF_ASCENT_CENTER) {

        xAdj = (float) -bounds.getWidth() / 2.0f;

    }
    else if (anchor == TextAnchor.TOP_RIGHT
            || anchor == TextAnchor.CENTER_RIGHT
            || anchor == TextAnchor.BOTTOM_RIGHT
            || anchor == TextAnchor.BASELINE_RIGHT
            || anchor == TextAnchor.HALF_ASCENT_RIGHT) {

        xAdj = (float) -bounds.getWidth();

    }

    if (anchor == TextAnchor.TOP_LEFT
            || anchor == TextAnchor.TOP_CENTER
            || anchor == TextAnchor.TOP_RIGHT) {

        yAdj = -descent - leading + (float) bounds.getHeight();

    }
    else if (anchor == TextAnchor.HALF_ASCENT_LEFT
            || anchor == TextAnchor.HALF_ASCENT_CENTER
            || anchor == TextAnchor.HALF_ASCENT_RIGHT) {

        yAdj = halfAscent;

    }
    else if (anchor == TextAnchor.CENTER_LEFT
            || anchor == TextAnchor.CENTER
            || anchor == TextAnchor.CENTER_RIGHT) {

        yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);

    }
    else if (anchor == TextAnchor.BASELINE_LEFT
            || anchor == TextAnchor.BASELINE_CENTER
            || anchor == TextAnchor.BASELINE_RIGHT) {

        yAdj = 0.0f;

    }
    else if (anchor == TextAnchor.BOTTOM_LEFT
            || anchor == TextAnchor.BOTTOM_CENTER
            || anchor == TextAnchor.BOTTOM_RIGHT) {

        yAdj = -metrics.getDescent() - metrics.getLeading();

    }
    if (textBounds != null) {
        textBounds.setRect(bounds);
    }
    result[0] = xAdj;
    result[1] = yAdj;
    return result;

}