c# - 如何在 .NET 中将缇转换为像素?

标签 c# graphics vb6-migration screen-resolution

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

最佳答案

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

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);
    }
}

要使用这些方法,只需执行以下操作(假设您处于 CreateGraphics 返回一个 Drawing.Graphics 对象的上下文中(此处 this 是一个Form,所以CreateGraphics继承自Form的父类(super class)Control):

using( Graphics g = CreateGraphics() )
{
    Width = g.ConvertTwipsToXPixels(sizeInTwips);
    Height = g.ConvertTwipsToYPixels(sizeInTwips);
}

请参阅 Graphics Class documentation 中的“备注”部分有关获取图形对象的方法列表。教程中提供了更完整的文档 How to: Create Graphics Objects .

最简单方法的简要总结:

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

关于c# - 如何在 .NET 中将缇转换为像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4044397/

相关文章:

c# - 从 RichTextBox 保存 RTF 时丢失表格宽度自动调整大小

java - 实现基于节点的图形 GUI 的最佳/最简单方法?

java - OpenGL:关闭除我指定的以外的所有照明?

javascript - 图形 beginBitmapFill easeljs

vb.net - 更改事件中的单选按钮检查状态

c# - 将 vb6 "Type"(struct) 转换为 c# 的最佳方法

c# - 如何关闭(杀死,释放?)处于 FIN_WAIT_2 状态的套接字?

c# - 相交和任何或包含和任何。找到至少一个公共(public)元素哪个更有效?

c# - 将桌面应用程序转换为 Web 应用程序

c# - ToggleSwitch.On & Off内容不更新