绘制尺寸为2X2英寸的矩形 - 凹槽到像素转换

时间:2015-12-24 09:05:04

标签: c# printing gdi+ system.drawing

我需要在纸张上打印一个大小为2X2英寸的矩形。

我知道我可以使用

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

此应用程序仅用于计算机。如何正确地将英寸转换为像素,以便在打印时可以获得所需的尺寸。

1 个答案:

答案 0 :(得分:1)

要默认情况下以正确的尺寸打印图像,它需要具有$_POST和像素的正确组合。

让我们看一个例子:

dpi

请注意,我必须将绘制尺寸中的1个像素减去// 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个像素!

enter image description here

请注意,我绘制的坐标取决于分辨率!还要注意jpeg格式如何创建大量模糊的颜色。 DrawRectangle可以创建更清晰的结果,尤其是打印文本后。

另请注意我必须缩小替代代码中的Png