PointToPixel

PointToPixel(double)

将点转换为 96 dpi 的像素。

public static double PointToPixel(double points)
范围类型描述
pointsDouble要转换的值。

评论

1 英寸等于 72 点。

例子

展示如何指定页面属性(以像素为单位)。

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// 部分的“页面设置”定义页边距的大小(以磅为单位)。
// 我们还可以使用“ConvertUtil”类来使用不同的测量单位,
// 例如定义边界时的像素。
PageSetup pageSetup = builder.PageSetup;
pageSetup.TopMargin = ConvertUtil.PixelToPoint(100);
pageSetup.BottomMargin = ConvertUtil.PixelToPoint(200);
pageSetup.LeftMargin = ConvertUtil.PixelToPoint(225);
pageSetup.RightMargin = ConvertUtil.PixelToPoint(125);

// 一个像素是 0.75 点。
Assert.AreEqual(0.75d, ConvertUtil.PixelToPoint(1));
Assert.AreEqual(1.0d, ConvertUtil.PointToPixel(0.75));

// 使用的默认 DPI 值为 96。
Assert.AreEqual(0.75d, ConvertUtil.PixelToPoint(1, 96));

// 添加内容以演示新的边距。
builder.Writeln($"This Text is {pageSetup.LeftMargin} points/{ConvertUtil.PointToPixel(pageSetup.LeftMargin)} pixels from the left, " +
                $"{pageSetup.RightMargin} points/{ConvertUtil.PointToPixel(pageSetup.RightMargin)} pixels from the right, " +
                $"{pageSetup.TopMargin} points/{ConvertUtil.PointToPixel(pageSetup.TopMargin)} pixels from the top, " +
                $"and {pageSetup.BottomMargin} points/{ConvertUtil.PointToPixel(pageSetup.BottomMargin)} pixels from the bottom of the page.");

doc.Save(ArtifactsDir + "UtilityClasses.PointsAndPixels.docx");

也可以看看


PointToPixel(double, double)

将点转换为指定像素分辨率的像素。

public static double PointToPixel(double points, double resolution)
范围类型描述
pointsDouble要转换的值。
resolutionDoubledpi(每英寸点数)分辨率。

评论

1 英寸等于 72 点。

例子

演示如何使用默认和自定义分辨率将点转换为像素。

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// 根据自定义 DPI 定义此部分上边距的大小(以像素为单位)。
const double myDpi = 192;

PageSetup pageSetup = builder.PageSetup;
pageSetup.TopMargin = ConvertUtil.PixelToPoint(100, myDpi);

Assert.AreEqual(37.5d, pageSetup.TopMargin, 0.01d);

// 默认 DPI 为 96 时,一个像素为 0.75 点。
Assert.AreEqual(0.75d, ConvertUtil.PixelToPoint(1));

builder.Writeln($"This Text is {pageSetup.TopMargin} points/{ConvertUtil.PointToPixel(pageSetup.TopMargin, myDpi)} " +
                $"pixels (at a DPI of {myDpi}) from the top of the page.");

// 设置新的 DPI 并相应调整上边距值。
const double newDpi = 300;
pageSetup.TopMargin = ConvertUtil.PixelToNewDpi(pageSetup.TopMargin, myDpi, newDpi);
Assert.AreEqual(59.0d, pageSetup.TopMargin, 0.01d);

builder.Writeln($"At a DPI of {newDpi}, the text is now {pageSetup.TopMargin} points/{ConvertUtil.PointToPixel(pageSetup.TopMargin, myDpi)} " +
                "pixels from the top of the page.");

doc.Save(ArtifactsDir + "UtilityClasses.PointsAndPixelsDpi.docx");

也可以看看