sighol
sighol

Reputation: 2818

Find pixel size of a glyph in WPF

I want to find the size in pixels for a glyph in WPF. That is the size of the glyph not including leading and trailing space. I want the size represented by the second ruler in the picture below. Is this possible?

Glyph size comparison

I have tried the procedure described in https://stackoverflow.com/a/12121990/111471, which resulted in the size represented by the first ruler. The code provided by that answer was:

var typeface = new GlyphTypeface(new Uri(fontpath));
var character = 'B';
var charIndex = typeface.CharacterToGlyphMap[character];

var width = typeface.AdvanceWidths[charIndex];
var height = typeface.Height - typeface.TopSideBearings[charIndex]
                             - typeface.BottomSideBearings[charIndex];

And then I found the pixel size by

var widthInEms = width * emSize;
var heightInEms = height * emSize;

Upvotes: 2

Views: 676

Answers (1)

Clemens
Clemens

Reputation: 128013

A simple way to get the width and height of a glyph would be to get the Size of the Bounds of its outline Geometry:

var size = typeface.GetGlyphOutline(charIndex, emSize, 0d).Bounds.Size;

Upvotes: 2

Related Questions