2017-05-09 142 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