2017-05-09 72 views
1

使用“缩放”布局背景图像时,实际宽度和高度并不总是与包含控件的宽度和高度相匹配,而不是“拉伸”布局。我想知道是否有一个属性或WinForms中的东西检索当前图像呈现的维度,而不做任何数学?使用“缩放”布局的背景图像的实际尺寸

+1

没有,我知道的。数学真的有那么吓人吗? – adv12

+0

@ adv12不,我喜欢数学,事实上,我已经在等待这个动物的时候做了它,但为什么要重新创造一个轮子? –

回答

1

这将返回从PictureBoxRectangle像素的任何SizeModes

但是,它确实需要一些数学缩放模式。

它可以很容易地适应相应的BackgroudImageLayout值:

Rectangle ImageArea(PictureBox pbox) 
{ 
    Size si = pbox.Image.Size; 
    Size sp = pbox.ClientSize; 

    if (pbox.SizeMode == PictureBoxSizeMode.StretchImage) return pbox.ClientRectangle; 
    if (pbox.SizeMode == PictureBoxSizeMode.Normal || 
     pbox.SizeMode == PictureBoxSizeMode.AutoSize) return new Rectangle(Point.Empty, si); 
    if (pbox.SizeMode == PictureBoxSizeMode.CenterImage) 
     return new Rectangle(new Point((sp.Width - si.Width)/2, 
          (sp.Height - si.Height)/2), si); 

    // PictureBoxSizeMode.Zoom 
    float ri = si.Width/si.Height; 
    float rp = sp.Width/sp.Height; 
    if (rp > ri) 
    { 
     int width = si.Width * sp.Height/si.Height; 
     int left = (sp.Width - width)/2; 
     return new Rectangle(left, 0, width, sp.Height); 
    } 
    else 
    { 
     int height = si.Height * sp.Width/si.Width; 
     int top = (sp.Height - height)/2; 
     return new Rectangle(0, top, sp.Width, height); 
    } 
} 
+0

有点看起来像我提出的,虽然有关'PictureBox' –

+0

True的问题中没有一个单词,但像'Panel'或'Label'这样的控件的BackgroundImageLayout基本上与'PictureBoxSizeMode相同',除了它没有'Tile'模式,但有一个'Autosize'模式。 – TaW