gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:24:14 25 4
gpt4 key购买 nike

我正在从事一个迁移项目,其中一个数据库实际上以缇为单位存储显示大小。由于我不能使用缇来为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com