I’m working on a migration project in which a database actually stores display sizes in twips.
Since I can’t use twips to assign sizes to WPF or Winforms controls, I was wondering if .NET has a conversion method usable at runtime?
I’m working on a migration project in which a database actually stores display sizes
Share
It turns out that the migration tool has something, but it wouldn’t do any good at runtime. Here’s what I did (if the hard-coded value in the extension method were changed to the value for points per inch it would work as a point converter too):
1 Twip = 1/1440th of an inch.
The .NET
Graphicsobject has a methodDpiXandDpiYwhich can be used to determine how many pixels are in an inch.Using those measurements I created the following extension methods for
Graphics:To use these methods one simply has to do the following (assuming you’re in a context where
CreateGraphicsreturns aDrawing.Graphicsobject (herethisis a Form, soCreateGraphicsis inherited fromForm‘s super-classControl):See the “Remarks” section in the
GraphicsClass documentation for a list of ways to obtain a graphics object. More complete documentation is available in the tutorial How to: Create Graphics Objects.Brief summary of easiest ways:
Control.CreateGraphicsPaintEventArgshas aGraphicsavailable in itsGraphicsproperty.Graphics.FromImagean image and it will return aGraphicsobject that can draw on that image. (NOTE: It is unlikely that you’ll want to use twips for an actual image)