Java Font Text Width stringWidth(String text, Font font)

Here you can find the source of stringWidth(String text, Font font)

Description

string Width

License

Apache License

Declaration

public static int stringWidth(String text, Font font) 

Method Source Code

//package com.java2s;
/*//from www  .j  a v a2s .c  om
 * Copyright 2000-2015 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.util.Map;

public class Main {
    private static final Graphics2D ourGraphics = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)
            .createGraphics();

    public static int stringWidth(String text, Font font) {
        setupAntialiasing(ourGraphics, true, true);
        return ourGraphics.getFontMetrics(font).stringWidth(text);
    }

    public static void setupAntialiasing(Graphics g2) {
        setupAntialiasing(g2, true, false);
    }

    public static void setupAntialiasing(Graphics g2, boolean enableAA, boolean ignoreSystemSettings) {
        if (g2 instanceof Graphics2D) {
            Graphics2D g = (Graphics2D) g2;
            Toolkit tk = Toolkit.getDefaultToolkit();
            //noinspection HardCodedStringLiteral
            Map map = (Map) tk.getDesktopProperty("awt.font.desktophints");

            if (map != null && !ignoreSystemSettings) {
                g.addRenderingHints(map);
            } else {
                g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                        enableAA ? RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR
                                : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
            }
        }
    }
}

Related

  1. stringPixelWidth(String text, FontMetrics fm)
  2. stringWidth(final FontMetrics fm, final String string)
  3. stringWidth(Graphics g, String s)
  4. stringWidth(Graphics2D g, String s)
  5. stringWidth(java.awt.Font font, String string)
  6. wrap(String str, FontMetrics fm, int maxWidth)
  7. wrapLineInto(String line, List list, FontMetrics fm, int maxWidth)