C# 控件上绘制可调透明度的图片,PictureBox为例

添加PictureBox控件的事件 - Paint,在控件重新绘制时发生的事件。

1private void pictureBox1_Paint(object sender, PaintEventArgs e)

2 {

3 Bitmap bitmap = new Bitmap(@"C:\Documents and Settings\Administrator\桌面\images\1234.jpg");

4

5 ChangePictureAlpha(e,bitmap,0.5f);

6 }

写一个方法,参数

PaintEventArgs e 绘制事件

Bitmap bitmap 覆盖的可变透明度的图片

float colorAlpha 透明度

方法可以根据不同的需要改变。

1 private void ChangePictureAlpha(PaintEventArgs e, Bitmap bitmap,float colorAlpha)

2 {

3 // Create the Bitmap object and load it with the texture image.

4 //Bitmap bitmap = new Bitmap("..\\..\\test.jpg");C:\Documents and Settings\Administrator\桌面\images

5 // Initialize the color matrix.

6 // Note the value 0.8 in row 4, column 4.

7 float[][] matrixItems ={

8 new float[] {1, 0, 0, 0, 0},

9 new float[] {0, 1, 0,0 , 0},

10 new float[] {0, 0, 1, 0, 0},

11 new float[] {0, 0, 0, colorAlpha, 0},

12 new float[] {0, 0, 0, 0, 1}};

13 ColorMatrix colorMatrix = new ColorMatrix(matrixItems);

14

15 // Create an ImageAttributes object and set its color matrix. 设置色调整矩阵

16 ImageAttributes imageAtt = new ImageAttributes();

17 imageAtt.SetColorMatrix(

18 colorMatrix,

19 ColorMatrixFlag.Default,

20 ColorAdjustType.Bitmap);

21

22 // Now draw the semitransparent bitmap image.

23 int iWidth = bitmap.Width;

24 int iHeight = bitmap.Height;

25 e.Graphics.DrawImage(

26 bitmap,

27 new Rectangle(0, 0, iWidth, iHeight), // destination rectangle 图片位置

28 0.0f, // source rectangle x

29 0.0f, // source rectangle y

30 iWidth, // source rectangle width

31 iHeight, // source rectangle height

32 GraphicsUnit.Pixel,

33 imageAtt);

34 }