Path: blob/master/src/java.desktop/share/classes/java/awt/FontMetrics.java
41152 views
/*1* Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.awt;2627import java.awt.font.FontRenderContext;28import java.awt.font.LineMetrics;29import java.awt.geom.Rectangle2D;30import java.io.Serial;31import java.text.CharacterIterator;3233/**34* The {@code FontMetrics} class defines a font metrics object, which35* encapsulates information about the rendering of a particular font on a36* particular screen.37* <p>38* <b>Note to subclassers</b>: Since many of these methods form closed,39* mutually recursive loops, you must take care that you implement40* at least one of the methods in each such loop to prevent41* infinite recursion when your subclass is used.42* In particular, the following is the minimal suggested set of methods43* to override in order to ensure correctness and prevent infinite44* recursion (though other subsets are equally feasible):45* <ul>46* <li>{@link #getAscent()}47* <li>{@link #getLeading()}48* <li>{@link #getMaxAdvance()}49* <li>{@link #charWidth(char)}50* <li>{@link #charsWidth(char[], int, int)}51* </ul>52* <p>53* <img src="doc-files/FontMetrics-1.gif" alt="The letter 'p' showing its 'reference point'"54* style="border:15px; float:right; margin: 7px 10px;">55* Note that the implementations of these methods are56* inefficient, so they are usually overridden with more efficient57* toolkit-specific implementations.58* <p>59* When an application asks to place a character at the position60* (<i>x</i>, <i>y</i>), the character is placed so that its61* reference point (shown as the dot in the accompanying image) is62* put at that position. The reference point specifies a horizontal63* line called the <i>baseline</i> of the character. In normal64* printing, the baselines of characters should align.65* <p>66* In addition, every character in a font has an <i>ascent</i>, a67* <i>descent</i>, and an <i>advance width</i>. The ascent is the68* amount by which the character ascends above the baseline. The69* descent is the amount by which the character descends below the70* baseline. The advance width indicates the position at which AWT71* should place the next character.72* <p>73* An array of characters or a string can also have an ascent, a74* descent, and an advance width. The ascent of the array is the75* maximum ascent of any character in the array. The descent is the76* maximum descent of any character in the array. The advance width77* is the sum of the advance widths of each of the characters in the78* character array. The advance of a {@code String} is the79* distance along the baseline of the {@code String}. This80* distance is the width that should be used for centering or81* right-aligning the {@code String}.82* <p>Note that the advance of a {@code String} is not necessarily83* the sum of the advances of its characters measured in isolation84* because the width of a character can vary depending on its context.85* For example, in Arabic text, the shape of a character can change86* in order to connect to other characters. Also, in some scripts,87* certain character sequences can be represented by a single shape,88* called a <em>ligature</em>. Measuring characters individually does89* not account for these transformations.90* <p>Font metrics are baseline-relative, meaning that they are91* generally independent of the rotation applied to the font (modulo92* possible grid hinting effects). See {@link java.awt.Font Font}.93*94* @author Jim Graham95* @see java.awt.Font96* @since 1.097*/98public abstract class FontMetrics implements java.io.Serializable {99100static {101/* ensure that the necessary native libraries are loaded */102Toolkit.loadLibraries();103if (!GraphicsEnvironment.isHeadless()) {104initIDs();105}106}107108private static final FontRenderContext109DEFAULT_FRC = new FontRenderContext(null, false, false);110111/**112* The actual {@link Font} from which the font metrics are113* created.114* This cannot be null.115*116* @serial117* @see #getFont()118*/119protected Font font;120121/**122* Use serialVersionUID from JDK 1.1 for interoperability.123*/124@Serial125private static final long serialVersionUID = 1681126225205050147L;126127/**128* Creates a new {@code FontMetrics} object for finding out129* height and width information about the specified {@code Font}130* and specific character glyphs in that {@code Font}.131* @param font the {@code Font}132* @see java.awt.Font133*/134protected FontMetrics(Font font) {135this.font = font;136}137138/**139* Gets the {@code Font} described by this140* {@code FontMetrics} object.141* @return the {@code Font} described by this142* {@code FontMetrics} object.143*/144public Font getFont() {145return font;146}147148/**149* Gets the {@code FontRenderContext} used by this150* {@code FontMetrics} object to measure text.151* <p>152* Note that methods in this class which take a {@code Graphics}153* parameter measure text using the {@code FontRenderContext}154* of that {@code Graphics} object, and not this155* {@code FontRenderContext}156* @return the {@code FontRenderContext} used by this157* {@code FontMetrics} object.158* @since 1.6159*/160public FontRenderContext getFontRenderContext() {161return DEFAULT_FRC;162}163164/**165* Determines the <em>standard leading</em> of the166* {@code Font} described by this {@code FontMetrics}167* object. The standard leading, or168* interline spacing, is the logical amount of space to be reserved169* between the descent of one line of text and the ascent of the next170* line. The height metric is calculated to include this extra space.171* @return the standard leading of the {@code Font}.172* @see #getHeight()173* @see #getAscent()174* @see #getDescent()175*/176public int getLeading() {177return 0;178}179180/**181* Determines the <em>font ascent</em> of the {@code Font}182* described by this {@code FontMetrics} object. The font ascent183* is the distance from the font's baseline to the top of most184* alphanumeric characters. Some characters in the {@code Font}185* might extend above the font ascent line.186* @return the font ascent of the {@code Font}.187* @see #getMaxAscent()188*/189public int getAscent() {190return font.getSize();191}192193/**194* Determines the <em>font descent</em> of the {@code Font}195* described by this196* {@code FontMetrics} object. The font descent is the distance197* from the font's baseline to the bottom of most alphanumeric198* characters with descenders. Some characters in the199* {@code Font} might extend200* below the font descent line.201* @return the font descent of the {@code Font}.202* @see #getMaxDescent()203*/204public int getDescent() {205return 0;206}207208/**209* Gets the standard height of a line of text in this font. This210* is the distance between the baseline of adjacent lines of text.211* It is the sum of the leading + ascent + descent. Due to rounding212* this may not be the same as getAscent() + getDescent() + getLeading().213* There is no guarantee that lines of text spaced at this distance are214* disjoint; such lines may overlap if some characters overshoot215* either the standard ascent or the standard descent metric.216* @return the standard height of the font.217* @see #getLeading()218* @see #getAscent()219* @see #getDescent()220*/221public int getHeight() {222return getLeading() + getAscent() + getDescent();223}224225/**226* Determines the maximum ascent of the {@code Font}227* described by this {@code FontMetrics} object. No character228* extends further above the font's baseline than this height.229* @return the maximum ascent of any character in the230* {@code Font}.231* @see #getAscent()232*/233public int getMaxAscent() {234return getAscent();235}236237/**238* Determines the maximum descent of the {@code Font}239* described by this {@code FontMetrics} object. No character240* extends further below the font's baseline than this height.241* @return the maximum descent of any character in the242* {@code Font}.243* @see #getDescent()244*/245public int getMaxDescent() {246return getDescent();247}248249/**250* For backward compatibility only.251* @return the maximum descent of any character in the252* {@code Font}.253* @see #getMaxDescent()254* @deprecated As of JDK version 1.1.1,255* replaced by {@code getMaxDescent()}.256*/257@Deprecated258public int getMaxDecent() {259return getMaxDescent();260}261262/**263* Returns an estimate of the maximum advance width of any character264* in the {@code Font} described by this {@code FontMetrics} object,265* with important caveats, enumerated below.266* <p>267* The advance is the distance from the leftmost point used to position268* the character to the rightmost point along the baseline.269* This is not the same thing as the visible width of the glyph image270* representing the character.271* <p>272* The advance of a {@code String} is not necessarily the sum of the273* advances of its characters. It may differ substantially if274* complex text layout is required for proper rendering.275* <p>276* Some of the caveats of the reported value include277* <ul>278* <li> The returned value is relying upon information from some279* underlying system font, and the correctness of that information280* is outside of AWT's control.281* <li> When specific characters are mapped into glyphs282* in some rendering context, instructions in the font itself283* together with the rasterization process may cause some glyph284* to have a wider advance than reported.285* <li> When a font is requested in some style, eg {@code Font.BOLD},286* for which no exact match is available, then techniques to satisfy287* the requested rendering may similarly result in glyphs that are288* wider than the reported maximum.289* <li> Depending on the implementation, an AWT logical font or290* physical font may need to locate some characters from one or more291* "fall back" fonts, when the primary underlying physical font does not292* support the character. These fonts may not all be known or considered293* in the calculation of the reported maximum advance. It is common294* for the design center of such fall back fonts to be for a different295* script than the design center of the primary font, so their296* advances can be quite different. This can also lead to the297* unexpected result that a font such as {@code Font.MONOSPACED} can298* render glyphs that are not all the same width.299* </ul>300* None of these caveats are exposed as they are all implementation details,301* and there is no practical way to determine when these are in effect.302* An application which needs a better estimate of the maximum advance,303* and knows the subset of characters it expects to display can query304* the advance of each such character to find the widest, however,305* as discussed above, since the displayed width of a {@code String}306* is not necessarily the sum of the advances the value still needs307* to be used with caution.308* <p>309* In summary, this method makes no absolute guarantee, nor can310* it even make a guarantee to be correct within some margin of error.311* So it should be used at most only for estimating the total space312* sufficient to display some number of as yet unknown characters from313* the font. And that might be either an overestimate, or an314* underestimate depending on the specific text and rendering conext.315* @return an estimate of the maximum advance width of any character316* in the {@code Font}, or {@code -1} if the317* maximum advance width is not known.318*/319public int getMaxAdvance() {320return -1;321}322323/**324* Returns the advance width of the specified character in this325* {@code Font}. The advance is the326* distance from the leftmost point to the rightmost point on the327* character's baseline. Note that the advance of a328* {@code String} is not necessarily the sum of the advances329* of its characters.330*331* <p>This method doesn't validate the specified character to be a332* valid Unicode code point. The caller must validate the333* character value using {@link334* java.lang.Character#isValidCodePoint(int)335* Character.isValidCodePoint} if necessary.336*337* @param codePoint the character (Unicode code point) to be measured338* @return the advance width of the specified character339* in the {@code Font} described by this340* {@code FontMetrics} object.341* @see #charsWidth(char[], int, int)342* @see #stringWidth(String)343*/344public int charWidth(int codePoint) {345if (!Character.isValidCodePoint(codePoint)) {346codePoint = 0xffff; // substitute missing glyph width347}348349if (codePoint < 256) {350return getWidths()[codePoint];351} else {352char[] buffer = new char[2];353int len = Character.toChars(codePoint, buffer, 0);354return charsWidth(buffer, 0, len);355}356}357358/**359* Returns the advance width of the specified character in this360* {@code Font}. The advance is the361* distance from the leftmost point to the rightmost point on the362* character's baseline. Note that the advance of a363* {@code String} is not necessarily the sum of the advances364* of its characters.365*366* <p><b>Note:</b> This method cannot handle <a367* href="../../../java.base/java/lang/Character.html#supplementary">368* supplementary characters</a>.369* To support all Unicode characters, including370* supplementary characters, use the {@link #charWidth(int)} method.371*372* @param ch the character to be measured373* @return the advance width of the specified character374* in the {@code Font} described by this375* {@code FontMetrics} object.376* @see #charsWidth(char[], int, int)377* @see #stringWidth(String)378*/379public int charWidth(char ch) {380if (ch < 256) {381return getWidths()[ch];382}383char[] data = {ch};384return charsWidth(data, 0, 1);385}386387/**388* Returns the total advance width for showing the specified389* {@code String} in this {@code Font}. The advance390* is the distance from the leftmost point to the rightmost point391* on the string's baseline.392* <p>393* Note that the advance of a {@code String} is394* not necessarily the sum of the advances of its characters.395* @param str the {@code String} to be measured396* @return the advance width of the specified {@code String}397* in the {@code Font} described by this398* {@code FontMetrics}.399* @throws NullPointerException if str is null.400* @see #bytesWidth(byte[], int, int)401* @see #charsWidth(char[], int, int)402* @see #getStringBounds(String, Graphics)403*/404public int stringWidth(String str) {405int len = str.length();406char[] data = new char[len];407str.getChars(0, len, data, 0);408return charsWidth(data, 0, len);409}410411/**412* Returns the total advance width for showing the specified array413* of characters in this {@code Font}. The advance is the414* distance from the leftmost point to the rightmost point on the415* string's baseline. The advance of a {@code String}416* is not necessarily the sum of the advances of its characters.417* This is equivalent to measuring a {@code String} of the418* characters in the specified range.419* @param data the array of characters to be measured420* @param off the start offset of the characters in the array421* @param len the number of characters to be measured from the array422* @return the advance width of the subarray of the specified423* {@code char} array in the font described by424* this {@code FontMetrics} object.425* @throws NullPointerException if {@code data} is null.426* @throws IndexOutOfBoundsException if the {@code off}427* and {@code len} arguments index characters outside428* the bounds of the {@code data} array.429* @see #charWidth(int)430* @see #charWidth(char)431* @see #bytesWidth(byte[], int, int)432* @see #stringWidth(String)433*/434public int charsWidth(char[] data, int off, int len) {435return stringWidth(new String(data, off, len));436}437438/**439* Returns the total advance width for showing the specified array440* of bytes in this {@code Font}. The advance is the441* distance from the leftmost point to the rightmost point on the442* string's baseline. The advance of a {@code String}443* is not necessarily the sum of the advances of its characters.444* This is equivalent to measuring a {@code String} of the445* characters in the specified range.446* @param data the array of bytes to be measured447* @param off the start offset of the bytes in the array448* @param len the number of bytes to be measured from the array449* @return the advance width of the subarray of the specified450* {@code byte} array in the {@code Font}451* described by452* this {@code FontMetrics} object.453* @throws NullPointerException if {@code data} is null.454* @throws IndexOutOfBoundsException if the {@code off}455* and {@code len} arguments index bytes outside456* the bounds of the {@code data} array.457* @see #charsWidth(char[], int, int)458* @see #stringWidth(String)459*/460@SuppressWarnings("deprecation")461public int bytesWidth(byte[] data, int off, int len) {462return stringWidth(new String(data, 0, off, len));463}464465/**466* Gets the advance widths of the first 256 characters in the467* {@code Font}. The advance is the468* distance from the leftmost point to the rightmost point on the469* character's baseline. Note that the advance of a470* {@code String} is not necessarily the sum of the advances471* of its characters.472* @return an array storing the advance widths of the473* characters in the {@code Font}474* described by this {@code FontMetrics} object.475*/476public int[] getWidths() {477int[] widths = new int[256];478for (char ch = 0 ; ch < 256 ; ch++) {479widths[ch] = charWidth(ch);480}481return widths;482}483484/**485* Checks to see if the {@code Font} has uniform line metrics. A486* composite font may consist of several different fonts to cover487* various character sets. In such cases, the488* {@code FontLineMetrics} objects are not uniform.489* Different fonts may have a different ascent, descent, metrics and490* so on. This information is sometimes necessary for line491* measuring and line breaking.492* @return {@code true} if the font has uniform line metrics;493* {@code false} otherwise.494* @see java.awt.Font#hasUniformLineMetrics()495*/496public boolean hasUniformLineMetrics() {497return font.hasUniformLineMetrics();498}499500/**501* Returns the {@link LineMetrics} object for the specified502* {@code String} in the specified {@link Graphics} context.503* @param str the specified {@code String}504* @param context the specified {@code Graphics} context505* @return a {@code LineMetrics} object created with the506* specified {@code String} and {@code Graphics} context.507* @see java.awt.Font#getLineMetrics(String, FontRenderContext)508*/509public LineMetrics getLineMetrics( String str, Graphics context) {510return font.getLineMetrics(str, myFRC(context));511}512513/**514* Returns the {@link LineMetrics} object for the specified515* {@code String} in the specified {@link Graphics} context.516* @param str the specified {@code String}517* @param beginIndex the initial offset of {@code str}518* @param limit the end offset of {@code str}519* @param context the specified {@code Graphics} context520* @return a {@code LineMetrics} object created with the521* specified {@code String} and {@code Graphics} context.522* @see java.awt.Font#getLineMetrics(String, int, int, FontRenderContext)523*/524public LineMetrics getLineMetrics( String str,525int beginIndex, int limit,526Graphics context) {527return font.getLineMetrics(str, beginIndex, limit, myFRC(context));528}529530/**531* Returns the {@link LineMetrics} object for the specified532* character array in the specified {@link Graphics} context.533* @param chars the specified character array534* @param beginIndex the initial offset of {@code chars}535* @param limit the end offset of {@code chars}536* @param context the specified {@code Graphics} context537* @return a {@code LineMetrics} object created with the538* specified character array and {@code Graphics} context.539* @see java.awt.Font#getLineMetrics(char[], int, int, FontRenderContext)540*/541public LineMetrics getLineMetrics(char [] chars,542int beginIndex, int limit,543Graphics context) {544return font.getLineMetrics(545chars, beginIndex, limit, myFRC(context));546}547548/**549* Returns the {@link LineMetrics} object for the specified550* {@link CharacterIterator} in the specified {@link Graphics}551* context.552* @param ci the specified {@code CharacterIterator}553* @param beginIndex the initial offset in {@code ci}554* @param limit the end index of {@code ci}555* @param context the specified {@code Graphics} context556* @return a {@code LineMetrics} object created with the557* specified arguments.558* @see java.awt.Font#getLineMetrics(CharacterIterator, int, int, FontRenderContext)559*/560public LineMetrics getLineMetrics(CharacterIterator ci,561int beginIndex, int limit,562Graphics context) {563return font.getLineMetrics(ci, beginIndex, limit, myFRC(context));564}565566/**567* Returns the bounds of the specified {@code String} in the568* specified {@code Graphics} context. The bounds is used569* to layout the {@code String}.570* <p>Note: The returned bounds is in baseline-relative coordinates571* (see {@link java.awt.FontMetrics class notes}).572* @param str the specified {@code String}573* @param context the specified {@code Graphics} context574* @return a {@link Rectangle2D} that is the bounding box of the575* specified {@code String} in the specified576* {@code Graphics} context.577* @see java.awt.Font#getStringBounds(String, FontRenderContext)578*/579public Rectangle2D getStringBounds( String str, Graphics context) {580return font.getStringBounds(str, myFRC(context));581}582583/**584* Returns the bounds of the specified {@code String} in the585* specified {@code Graphics} context. The bounds is used586* to layout the {@code String}.587* <p>Note: The returned bounds is in baseline-relative coordinates588* (see {@link java.awt.FontMetrics class notes}).589* @param str the specified {@code String}590* @param beginIndex the offset of the beginning of {@code str}591* @param limit the end offset of {@code str}592* @param context the specified {@code Graphics} context593* @return a {@code Rectangle2D} that is the bounding box of the594* specified {@code String} in the specified595* {@code Graphics} context.596* @see java.awt.Font#getStringBounds(String, int, int, FontRenderContext)597*/598public Rectangle2D getStringBounds( String str,599int beginIndex, int limit,600Graphics context) {601return font.getStringBounds(str, beginIndex, limit,602myFRC(context));603}604605/**606* Returns the bounds of the specified array of characters607* in the specified {@code Graphics} context.608* The bounds is used to layout the {@code String}609* created with the specified array of characters,610* {@code beginIndex} and {@code limit}.611* <p>Note: The returned bounds is in baseline-relative coordinates612* (see {@link java.awt.FontMetrics class notes}).613* @param chars an array of characters614* @param beginIndex the initial offset of the array of615* characters616* @param limit the end offset of the array of characters617* @param context the specified {@code Graphics} context618* @return a {@code Rectangle2D} that is the bounding box of the619* specified character array in the specified620* {@code Graphics} context.621* @see java.awt.Font#getStringBounds(char[], int, int, FontRenderContext)622*/623public Rectangle2D getStringBounds( char [] chars,624int beginIndex, int limit,625Graphics context) {626return font.getStringBounds(chars, beginIndex, limit,627myFRC(context));628}629630/**631* Returns the bounds of the characters indexed in the specified632* {@code CharacterIterator} in the633* specified {@code Graphics} context.634* <p>Note: The returned bounds is in baseline-relative coordinates635* (see {@link java.awt.FontMetrics class notes}).636* @param ci the specified {@code CharacterIterator}637* @param beginIndex the initial offset in {@code ci}638* @param limit the end index of {@code ci}639* @param context the specified {@code Graphics} context640* @return a {@code Rectangle2D} that is the bounding box of the641* characters indexed in the specified {@code CharacterIterator}642* in the specified {@code Graphics} context.643* @see java.awt.Font#getStringBounds(CharacterIterator, int, int, FontRenderContext)644*/645public Rectangle2D getStringBounds(CharacterIterator ci,646int beginIndex, int limit,647Graphics context) {648return font.getStringBounds(ci, beginIndex, limit,649myFRC(context));650}651652/**653* Returns the bounds for the character with the maximum bounds654* in the specified {@code Graphics} context.655* @param context the specified {@code Graphics} context656* @return a {@code Rectangle2D} that is the657* bounding box for the character with the maximum bounds.658* @see java.awt.Font#getMaxCharBounds(FontRenderContext)659*/660public Rectangle2D getMaxCharBounds(Graphics context) {661return font.getMaxCharBounds(myFRC(context));662}663664private FontRenderContext myFRC(Graphics context) {665if (context instanceof Graphics2D) {666return ((Graphics2D)context).getFontRenderContext();667}668return DEFAULT_FRC;669}670671672/**673* Returns a representation of this {@code FontMetrics}674* object's values as a {@code String}.675* @return a {@code String} representation of this676* {@code FontMetrics} object.677*/678public String toString() {679return getClass().getName() +680"[font=" + getFont() +681"ascent=" + getAscent() +682", descent=" + getDescent() +683", height=" + getHeight() + "]";684}685686/**687* Initialize JNI field and method IDs688*/689private static native void initIDs();690}691692693