绘制大小为 2X2 英寸的矩形 - 英寸到像素的转换

Drawing a Rectangle of Size 2X2 Inches -Inches to Pixel Conversion

我需要绘制一个矩形,打印在纸上时大小应为 2X2 英寸。

我知道我可以使用

画一个矩形
 g.DrawRectangle(pen, 100,100, 100, 200);

此应用程序将仅用于 computers.How 我能否将英寸正确转换为像素,以便在打印时获得所需的尺寸。

要使图像在默认情况下以正确的尺寸打印,需要 dpi 和像素的正确组合。

我们来看一个例子:

// aiming at 150dpi and 4x6 inches:
float dpi = 150;
float width = 4;
float height = 6;

using (Bitmap bmp = new Bitmap((int)(dpi * width), (int)(dpi * height)))
{
    // first set the resolution
    bmp.SetResolution(dpi, dpi);
    // then create a suitable Graphics object:
    using (Graphics G = Graphics.FromImage(bmp))
    using (Pen pen = new Pen(Color.Orange))
    {
        pen.Alignment = System.Drawing.Drawing2D.PenAlignment.Center;
        G.Clear(Color.FloralWhite);
        // using pixels here:

        Size sz = new System.Drawing.Size((int)dpi * 2 - 1, (int)dpi * 2 - 1);
        G.DrawRectangle(pen, new Rectangle(new Point(0, 0), sz));
        G.DrawRectangle(pen, new Rectangle(new Point(0, 300), sz));
        G.DrawRectangle(pen, new Rectangle(new Point(0, 600), sz));
        G.DrawRectangle(pen, new Rectangle(new Point(300, 0), sz));
        G.DrawRectangle(pen, new Rectangle(new Point(300, 300), sz));
        G.DrawRectangle(pen, new Rectangle(new Point(300, 600), sz));

        // alternative code:
        // we can also set the Graphics object to measure stuff in inches;
        G.PageUnit = GraphicsUnit.Inch;
        // or fractions of it, let's use 10th:
        G.PageScale = 0.1f;
        using (Pen pen2 = new Pen(Color.MediumPurple, 1f / dpi * G.PageScale))
        {
            // draw one rectangle offset by an inch:
            G.DrawRectangle(pen2, 10f, 10f, 20f, 20f);
        }

        bmp.Save(@"D:\xxx.jpg", ImageFormat.Jpeg);
    }
}

请注意,我必须从绘制尺寸中减去 1 个像素,因为 DrawRectangle overdraws 1 个像素!

请注意,我绘制的坐标取决于分辨率!另请注意 jpeg 格式如何产生大量模糊的颜色。 Png创建更清晰的结果,尤其是在打印文本时..

另请注意我必须如何缩小替代代码中的 PenWidth