When you create a custom ASP.NET control most of the times you inherit it from WebControl class or one of it's derivatives. Among other properties WebControl has a Font property of FontInfo type which in turn has a Size property of FontUnit type. Users can set the yourControl.Font.Size to any HTML/CSS compatible value from 12pt to 1.2em to x-large.
This is all fine while your control outputs plain HTML. But at this moment I'm working on a controls which use Flash controls as their output and Flash knows nothing about font sizes in points let alone x-small & co. (at least I was told so by my flash developer colleague). So what I needed was a way to convert all the reasonable FontUnit values to some more or less equivalent pixel sizes. So after some experiments I came up with this FontSizeConverter class with only one static method to convert FontUnit to pixels.
Keep in mind that this is only a raw approximation and doesn't pretend to be completely correct and universal solution. Em and Percentage values use 16px as base.
public class FontSizeConverter
{
public static int ToPixels(FontUnit unitSize)
{
int result = 16;
if (unitSize.Type != FontSize.NotSet && unitSize.Type != FontSize.AsUnit)
{
// size in x-small, etc
switch (unitSize.Type)
{
case FontSize.XXSmall:
result = 9;
break;
case FontSize.XSmall:
result = 10;
break;
case FontSize.Smaller:
case FontSize.Small:
result = 13;
break;
case FontSize.Medium:
result = 16;
break;
case FontSize.Large:
case FontSize.Larger:
result = 18;
break;
case FontSize.XLarge:
result = 24;
break;
case FontSize.XXLarge:
result = 32;
break;
default:
result = 16;
break;
}
}
else if (unitSize.Type == FontSize.AsUnit)
{
switch (unitSize.Unit.Type)
{
case UnitType.Pixel:
result = (int)Math.Round(unitSize.Unit.Value);
break;
case UnitType.Point:
result = (int)Math.Round(unitSize.Unit.Value*1.33);
break;
case UnitType.Em:
result = (int)Math.Round(unitSize.Unit.Value * 16);
break;
case UnitType.Percentage:
result = (int)Math.Round(unitSize.Unit.Value * 16 / 100);
break;
default:
// other types are not supported. just return the medium
result = 16;
break;
}
}
return result;
}
}
