views:

53

answers:

1

I'm working on a migration project in which a database actually stores display sizes in twips. Since I can't use twips in .NET, I was wondering if .NET has a conversion method usable at runtime?

Near as I can tell no one has asked this question yet. I've already figured it out, so I figured I'd post in case someone else had a better solution or in case someone wanted to use mine.

+8  A: 

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 Graphics object has a method DpiX and DpiY which can be used to determine how many pixels are in an inch. Using those measurements I created the following extension methods for Graphics:

using System.Drawing;

static class Extensions
{
    /// <summary>
    /// Converts an integer value in twips to the corresponding integer value
    /// in pixels on the x-axis.
    /// </summary>
    /// <param name="source">The Graphics context to use</param>
    /// <param name="inTwips">The number of twips to be converted</param>
    /// <returns>The number of pixels in that many twips</returns>
    public static int ConvertTwipsToXPixels(this Graphics source, int twips)
    {
        return (int)(((double)twips) * (1.0 / 1440.0) * source.DpiX);
    }

    /// <summary>
    /// Converts an integer value in twips to the corresponding integer value
    /// in pixels on the y-axis.
    /// </summary>
    /// <param name="source">The Graphics context to use</param>
    /// <param name="inTwips">The number of twips to be converted</param>
    /// <returns>The number of pixels in that many twips</returns>
    public static int ConvertTwipsToYPixels(this Graphics source, int twips)
    {
        return (int)(((double)twips) * (1.0 / 1440.0) * source.DpiY);
    }
}

To use these methods one simple has to do the following (assuming you're in a context where "CreateGraphics" returns a Drawing.Graphics object:

using( Graphics g = CreateGraphics() )
{
    Width = g.ConvertTwipsToXPixels(sizeInTwips);
    Height = g.ConvertTwipsToYPixels(sizeInTwips);
}
Cpfohl
got a small error in your code. In the ConvertTwipsToYPixles, you have it using the DipX instead of the DpiY
Wesley
Thanks! Appreciate the watchful eyes. +1, vote me up if you think it's helpful.
Cpfohl