Gets kerning offset for two characters of the font - Java 2D Graphics

Java examples for 2D Graphics:Font

Description

Gets kerning offset for two characters of the font

Demo Code

/*/*from   w w w.  j a v  a 2  s.com*/
 *  Copyright (C) 2010-2015 JPEXS, All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3.0 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.
 */
//package com.java2s;
import java.awt.Font;

import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.TextAttribute;

import java.text.AttributedCharacterIterator;

import java.util.HashMap;

import java.util.Map;
import javax.swing.JPanel;

public class Main {
    /**
     * Gets kerning offset for two characters of the font
     *
     * @param font Font
     * @param char1 First character
     * @param char2 Second character
     * @return offset
     */
    public static int getFontCharsKerning(Font font, char char1, char char2) {
        char[] chars = new char[] { char1, char2 };
        Map<AttributedCharacterIterator.Attribute, Object> withKerningAttrs = new HashMap<>();

        withKerningAttrs.put(TextAttribute.FONT, font);
        withKerningAttrs.put(TextAttribute.KERNING,
                TextAttribute.KERNING_ON);
        Font withKerningFont = Font.getFont(withKerningAttrs);
        GlyphVector withKerningVector = withKerningFont.layoutGlyphVector(
                getFontRenderContext(withKerningFont), chars, 0,
                chars.length, Font.LAYOUT_LEFT_TO_RIGHT);
        int withKerningX = withKerningVector.getGlyphLogicalBounds(1)
                .getBounds().x;

        Map<AttributedCharacterIterator.Attribute, Object> noKerningAttrs = new HashMap<>();
        noKerningAttrs.put(TextAttribute.FONT, font);
        noKerningAttrs.put(TextAttribute.KERNING, 0);
        Font noKerningFont = Font.getFont(noKerningAttrs);
        GlyphVector noKerningVector = noKerningFont.layoutGlyphVector(
                getFontRenderContext(noKerningFont), chars, 0,
                chars.length, Font.LAYOUT_LEFT_TO_RIGHT);
        int noKerningX = noKerningVector.getGlyphLogicalBounds(1)
                .getBounds().x;
        return withKerningX - noKerningX;
    }

    private static FontRenderContext getFontRenderContext(Font font) {
        return (new JPanel()).getFontMetrics(font).getFontRenderContext();
    }
}

Related Tutorials