2012-06-09 36 views
0

我有大小1000,20一個圖片,我設置它的位圖,像這樣的Form_Load事件:當我將PictureBox的BorderStyle設置爲FixedSingle時,爲什麼我的位圖縮放會發生變化?

void Form1_Load (object sender, EventArgs e) 
{ 
    SetProgressBar (pictureBox1, 25); 
} 

void SetProgressBar (PictureBox pb, int progress) 
{ 
    Bitmap bmp = new Bitmap (100, 1); 

    using (Graphics gfx = Graphics.FromImage (bmp)) 
    using (SolidBrush brush = new SolidBrush (System.Drawing.SystemColors.ButtonShadow)) 
    { 
     gfx.FillRectangle (brush, 0, 0, 100, 1); 
    } 

    for (int i = 0; i < progress; ++i) 
    { 
     bmp.SetPixel (i, 0, Color.DeepSkyBlue); 
    } 

    // If I don't set the resize bitmap size to height * 2, then it doesn't fill the whole image for some reason. 
    pb.Image = ResizeBitmap (bmp, pb.Width, pb.Height * 2, progress); 
} 

public Bitmap ResizeBitmap (Bitmap b, int nWidth, int nHeight, int progress) 
{ 
    Bitmap result = new Bitmap (nWidth, nHeight); 

    StringFormat sf = new StringFormat (); 
    sf.Alignment = StringAlignment.Center; 
    sf.LineAlignment = StringAlignment.Center; 
    Font font = new Font (FontFamily.GenericSansSerif, 10, FontStyle.Regular); 

    using (Graphics g = Graphics.FromImage ((Image) result)) 
    { 
      // 20 is the height of the picturebox 
     g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; 
     g.DrawImage (b, 0, 0, nWidth, nHeight); 
     g.DrawString (progress.ToString (), font, Brushes.White, new RectangleF (0, -1, nWidth, 20), sf); 
    } 
    return result; 
} 

一切看起來不錯,直到我設置的邊框來FlatSingle。它最終造成了差距。我怎樣才能解決這個問題,所以它仍然看起來完全是彩色的?

編輯:這是它的外觀:

enter image description here

+0

爲什麼會有'height * 2'和'-1'和'18'來自哪裏?這樣的事情值得評論。無論是在真實的代碼,特別是在一個問題。 –

+0

我爲兩者添加了評論。如果沒有高度* 2,它只能垂直填充圖片框的一半。不知道爲什麼它這樣做。 –

回答

2

看來,增加您pictureboxes規模增加的邊界。我設置了BorderStyle設置爲FixedSingle,None和Fixed3D的示例,每個結果都不相同。這些PictureBox中的每一個都從相同的位置開始,您可以看到可見寬度實際發生了變化。

enter image description here

它計算出爲約4個像素的pn的FixedSingle和2個像素的Fixed3D。我不確定發生了什麼,但你應該可以像這樣編碼。

if (pb.BorderStyle == BorderStyle.FixedSingle) 
    pb.Image = ResizeBitmap(bmp, pb.Width + 4, pb.Height * 2, progress); 
else if (pb.BorderStyle == BorderStyle.Fixed3D) 
    pb.Image = ResizeBitmap(bmp, pb.Width + 2, pb.Height * 2, progress); 
else 
    pb.Image = ResizeBitmap(bmp, pb.Width, pb.Height * 2, progress); 

這給出了一個看起來像這樣的結果。

enter image description here


如果你看一下DisplayRectangle屬性,你會看到,當你改變你的邊框客戶矩形變化:

BorderStyle.None = 1000個像素
邊框。 Fixed3D = 996像素
BorderStyle.FixedSingle = 998像素

+0

非常感謝,現在效果很好。 –

相關問題