2013-09-23 18 views
0

這個想法是在Visual Studio 2010中使用C#構建Windows窗體應用程序。使圖像在窗體上緩慢顯示

當用戶點擊一個按鈕時,程序將運行一系列操作。

是否可以使用圖像來顯示進度而不是使用進度條?

所以這個想法是,圖像將開始變得不可見,隨着程序的進展,圖像變得越來越明顯。

0% - invisible 
50% - half transparent 
100% - visible 

我知道你可以切換圖片框是可見或不可見(PictureBox.Visible = true或false),但有沒有辦法讓它在兩者之間?

任何想法都很感激。

+1

[.DrawImage with opacity?]的可能重複?(http://stackoverflow.com/questions/5519956/drawimage-with-opacity) –

+0

你想要什麼可以通過'splash from'指示進度來實現。難道不簡單嗎? –

+0

[這是一個類似的問題](http://stackoverflow.com/questions/918353/c-sharp-alpha-blend-transparent-picturebox),它聽起來像它會變得醜陋 – Jonesopolis

回答

0

中的WinForms處理圖像速度很慢,所以這樣做盡可能少:

public Bitmap ImageFade(Bitmap sourceBitmap, byte Transparency) 
    { 
     BitmapData sourceData = sourceBitmap.LockBits(new Rectangle(0, 0, 
            sourceBitmap.Width, sourceBitmap.Height), 
            ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); 

     byte[] pixelBuffer = new byte[sourceData.Stride * sourceData.Height]; 
     byte[] resultBuffer = new byte[sourceData.Stride * sourceData.Height]; 

     Marshal.Copy(sourceData.Scan0, pixelBuffer, 0, pixelBuffer.Length); 

     sourceBitmap.UnlockBits(sourceData); 

     byte blue = 0; 
     byte green = 0; 
     byte red = 0; 
     byte a = 0; 

     int byteOffset = 0; 

     for (int offsetY = 0; offsetY < 
      sourceBitmap.Height; offsetY++) 
     { 
      for (int offsetX = 0; offsetX < 
       sourceBitmap.Width; offsetX++) 
      { 
       blue = 0; 
       green = 0; 
       red = 0; 
       a = 0; 

       byteOffset = offsetY * 
           sourceData.Stride + 
           offsetX * 4; 

       blue += pixelBuffer[byteOffset]; 
       green += pixelBuffer[byteOffset + 1]; 
       red += pixelBuffer[byteOffset + 2]; 
       a += Transparency;//pixelBuffer[byteOffset + 3]; 

       resultBuffer[byteOffset] = blue; 
       resultBuffer[byteOffset + 1] = green; 
       resultBuffer[byteOffset + 2] = red; 
       resultBuffer[byteOffset + 3] = a; 
      } 
     } 

     Bitmap resultBitmap = new Bitmap(sourceBitmap.Width, sourceBitmap.Height); 

     BitmapData resultData = resultBitmap.LockBits(new Rectangle(0, 0, 
           resultBitmap.Width, resultBitmap.Height), 
           ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); 

     Marshal.Copy(resultBuffer, 0, resultData.Scan0, resultBuffer.Length); 
     resultBitmap.UnlockBits(resultData); 

     return resultBitmap; 
    } 

我注意到另外一個答案使用SetPixel 。如果可能,避免使用該功能。編輯底層字節流要快得多,因爲它不是硬件加速的,所以它仍然很慢,但它是幾個非常好的選項中的最佳選擇。

此功能可能會進一步優化,但我將其作爲練習讀者

0

你總是可以調整圖像的alpha成分:

void SetImageProgress(float percent, Bitmap img) 
{ 
    int alpha = (int)(percent/100.0f * 255.0f); 
    alpha &= 0xff; 
    for(int x = 0; x < img.Width; x++) 
    { 
     for(int y = 0; y < img.Height; y++) 
     { 
     Color c = img.GetPixel(x, y); 
     c = Color.FromArgb(alpha, c.R, c.G, c.B); 
     img.SetPixel(x, y, c); 
     } 
    } 
}