graphics.getFontMetrics()

Type Function
Library graphics.*
Return value Table
Revision Release 2022.3683
Keywords fonts, text, metrics, graphics
See also Using Custom Fonts
object.baselineOffset

Overview

This function calculates and returns the various metrics for the font with the given name (file name) and text size. The returned value is a table containing the following properties:

Syntax

graphics.getFontMetrics( fontName [, fontSize] )
fontName (required)

String. The name of the font, for example "Times New Roman", "DroidSansMono", or "Monaco". Alternatively, this can point to an actual font file as in "CoolCustomFont.ttf". See the Using Custom Fonts guide for more details on using custom fonts in Corona.

fontSize (optional)

Number. The desired font size in points.

Example

local font = "Avenir"
local fontSize = 100

local text = display.newText( "jKf", display.contentCenterX, display.contentCenterY-120, font, fontSize )

local metrics = graphics.getFontMetrics( font, fontSize )

print( "ASCENT:", metrics.ascent )
print( "DESCENT:", metrics.descent )
print( "LEADING:", metrics.leading )
print( "HEIGHT:", metrics.height )
print( "BASELINE OFFSET:", text.baselineOffset )

local textVertCenter = display.newRect( display.contentCenterX, display.contentCenterY-120, 240, 1 )
textVertCenter:setFillColor( 0.3 )

local baseline = display.newRect( display.contentCenterX, textVertCenter.y-text.baselineOffset, 300, 1 )
baseline:setFillColor( 0.93, 0.1, 0.14 )

local ascent = display.newRect( display.contentCenterX, baseline.y-metrics.ascent, 300, 1 )
ascent:setFillColor( 0.66, 0.39, 0.66 )

local height = display.newRect( display.contentCenterX, ascent.y+metrics.height, 300, 1 )
height:setFillColor( 0.66, 0.39, 0.66 )

local descent = display.newRect( display.contentCenterX+15, baseline.y-metrics.descent, 270, 1 )
descent:setFillColor( 0.27, 0.55, 0.8 )

text:toFront()