blob: aaf41c2288dc4b2a13c0b9bd6c40ca4bb446e3eb [file] [log] [blame]
/*********************************************************************************
* Copyright (c) 2020 Robert Bosch GmbH and others.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Robert Bosch GmbH - initial API and implementation
********************************************************************************
*/
package org.eclipse.app4mc.amalthea.visualizations.standard.util;
import javafx.geometry.Bounds;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
/**
* Helper class to calculate metrics based on a {@link Font}.
*/
public class FontMetrics {
private final Text internal = new Text();
public final double lineHeight;
public final double ascent;
public final double descent;
/**
* Create a new {@link FontMetrics} object for the given {@link Font}.
*
* @param font The {@link Font} for which the {@link FontMetrics} class should
* be created.
*/
public FontMetrics(Font font) {
internal.setFont(font);
Bounds bounds = internal.getLayoutBounds();
lineHeight = bounds.getHeight();
ascent = -bounds.getMinY();
descent = bounds.getMaxY();
}
/**
* The width needed for a given text.
*
* @param txt The text for which the width is requested.
* @return The width of the given text for the configured {@link Font}.
*/
public double computeStringWidth(String txt) {
internal.setText(txt);
return internal.getLayoutBounds().getWidth();
}
}