中的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 。如果可能,避免使用該功能。編輯底層字節流要快得多,因爲它不是硬件加速的,所以它仍然很慢,但它是幾個非常好的選項中的最佳選擇。
此功能可能會進一步優化,但我將其作爲練習讀者
[.DrawImage with opacity?]的可能重複?(http://stackoverflow.com/questions/5519956/drawimage-with-opacity) –
你想要什麼可以通過'splash from'指示進度來實現。難道不簡單嗎? –
[這是一個類似的問題](http://stackoverflow.com/questions/918353/c-sharp-alpha-blend-transparent-picturebox),它聽起來像它會變得醜陋 – Jonesopolis