2012-07-20 78 views
4

任何人都可以告诉我如何从像素以外的任何单位的GetBounds获取矩形?下面的代码 - 直接从MSDN文档中提取这个函数 - 返回一个相当明显的像素点而不是点(1/72英寸)的矩形。 (除非像我认为的那样,图标大小为32/72“x32/72”,而不是32x32像素)。我最感兴趣的是以英寸为单位的矩形,但是我只想看到GetBounds pageUnit参数导致返回的矩形发生变化。System.Drawing.Bitmap GetBounds GraphicsUnit.Inch

Bitmap bitmap1 = Bitmap.FromHicon(SystemIcons.Hand.Handle); 
Graphics formGraphics = this.CreateGraphics(); 
GraphicsUnit units = GraphicsUnit.Point; 

RectangleF bmpRectangleF = bitmap1.GetBounds(ref units); 
Rectangle bmpRectangle = Rectangle.Round(bmpRectangleF); 
formGraphics.DrawRectangle(Pens.Blue, bmpRectangle); 
formGraphics.Dispose(); 
+1

这是声明中的一个错误,参数是* out *,not * ref *。最好的做法是使用宽度/高度。 – 2012-07-21 00:12:21

+0

不,尝试使用'out'关键字会产生错误。我很难转换单位,但如果它有效,这会更容易。 – 2012-08-08 15:46:25

回答

4

的信息是对这个有点稀疏,我能找到这个MSDN Forum posting因为位图已经创建单位已经设置并没有多变的那个建议。由于GraphicsUnit正在通过参考传递,因此您在通话后查看它,您会发现它从Inch开始设置为Pixel。如果您实际上想要更改矩形绘制的大小,请将Graphics.PageUnit Property设置为formGraphics,将GraphicsUnit设置为您想要绘制矩形。

从以上链接:

在此示例中,Image.GetBounds方法的参数不改变结果,由于结合的位图的已经决定。参数仅确定处理范围的单位长度,单位为英寸或逐点。但参数不会影响的结果。

重点煤矿

+0

MSDN文档示例在对示例中使用的图像进行硬编码并知道该图像的单元时,会明确初始化单元以“点”,这没有任何意义。此外,GetBounds方法的文档说:获取指定单元中图像的边界。这几乎肯定是(nother)GDI +错误。转换单位知道分辨率没有问题,但我发现大图像的错误,放弃了,并开始使用WPF。 – 2012-08-08 15:44:06

1

有点晚了回答这个问题,但我觉得要回答这个问题:“我有多少的mm可以适合我的图片框的时候我会做,因为我发现它在谷歌? “,这将为我节省大量时间,而不必制定如何去做!的getBounds是无用的(如果你想它以像素为单位...),但它是可以找到使用Graphics.TransformPoints方法绘图单位和显示像素之间的关系:

private void Form1_Load(object sender, EventArgs e) 
    { 
     Bitmap b; 
     Graphics g; 
     Size s = pictureBox1.Size; 
     b = new Bitmap(s.Width, s.Height); 
     g = Graphics.FromImage(b); 
     PointF[] points = new PointF[2]; 
     g.PageUnit = GraphicsUnit.Millimeter; 
     g.PageScale = 1.0f; 
     g.ScaleTransform(1.0f, 1.0f); 
     points[0] = new PointF(0, 0); 
     points[1] = new PointF(1, 1); 
     g.TransformPoints(CoordinateSpace.Device, CoordinateSpace.Page, points); 
     MessageBox.Show(String.Format("1 page unit in {0} is {1} pixels",g.PageUnit.ToString(),points[1].X)); 
     points[0] = new PointF(0, 0); 
     points[1] = new PointF(1, 1); 
     g.TransformPoints(CoordinateSpace.Page, CoordinateSpace.World, points); 
     MessageBox.Show(String.Format("1 page unit in {0} is {1} pixels",g.PageUnit.ToString(),points[1].X)); 
     g.ResetTransform(); 
     pictureBox1.Image = b; 
     SolidBrush brush = new SolidBrush(Color.FromArgb(120, Color.Azure)); 
     Rectangle rectangle = new Rectangle(10, 10, 50, 50); 
     // Fill in the rectangle with a semi-transparent color. 
     g.FillRectangle(brush, rectangle); 
     pictureBox1.Invalidate(); 

    } 

这将显示基本毫米显示像素(在我的情况下是3.779527) - 世界坐标是每像素1毫米,如果你应用graphics.ScaleTransform,这将会改变。

编辑:当然,如果将位图分配给pictureBox图像属性(并使Graphics对象允许根据需要进行更改),它会有所帮助。

相关问题