如何在.NET中将Twips转换为像素?

Cri*_*ole 24 c# graphics vb6-migration screen-resolution

我正在进行一个迁移项目,其中数据库实际上以缇为单位存储显示大小.由于我不能使用twips为WPF或Winforms控件分配大小,我想知道.NET是否有在运行时可用的转换方法?

Cri*_*ole 28

事实证明,迁移工具有一些东西,但它在运行时不会有任何好处.这就是我所做的(如果扩展方法中的硬编码值更改为每英寸点的值,它也可以用作点转换器):

1缇= 1/1440英寸.在.NET Graphics对象有一个方法DpiXDpiY可用于确定有多少像素在一英寸.使用这些测量我创建了以下扩展方法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);
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用这些方法,只需要执行以下操作(假设您处于CreateGraphics返回Drawing.Graphics对象的上下文中(此处this为Form,因此CreateGraphicsForm超类继承Control):

using( Graphics g = CreateGraphics() )
{
    Width = g.ConvertTwipsToXPixels(sizeInTwips);
    Height = g.ConvertTwipsToYPixels(sizeInTwips);
}
Run Code Online (Sandbox Code Playgroud)

有关获取图形对象的方法列表,请参阅Graphics类文档中的"备注"部分.教程如何:创建图形对象中提供了更完整的文档.

最简单方法的简要总结:

  • Control.CreateGraphics
  • Paint事件的PaintEventArgs具有Graphics可在其Graphics属性.
  • 处理Graphics.FromImage一个图像,它将返回一个Graphics可以在该图像上绘制的对象.(注意:您不太可能想要使用缇实际图像)

  • 你的代码中出现了一个小错误.在ConvertTwipsToYPixles中,您可以使用DipX而不是DpiY (2认同)

小智 5

对于迁移项目,我们可以使用内置的会话支持功能

microsoft.visualbasic.compatibility.vb6.twipsperpixelx
microsoft.visualbasic.compatibility.vb6.twipsperpixely
Run Code Online (Sandbox Code Playgroud)