本帖最后由 小红帽 于 2014-7-30 14:09 编辑
LayeredSkin的渐变透明动画特效就是采用该算法实现的,使用案例已添加!
腾讯QQ的效果是一块块的
[C#] 纯文本查看 复制代码 /// <summary>
/// 渐变透明
/// </summary>
/// <param name="srcImage">原图</param>
/// <param name="rect">需要渐变处理的区域</param>
/// <param name="direction">渐变方向透明到不透明 0:上到下,1:下到上,2:左到右,3右到左</param>
/// <returns></returns>
public static Image GradualAlpha(Image srcImage, Rectangle rect, int direction)
{
Bitmap bmp = new Bitmap(srcImage);
double opacity = 1;//不透明度的百分比
//LockBits将Bitmap锁定到内存中
BitmapData data = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
unsafe
{
//p指向地址
byte* p = (byte*)data.Scan0;//8位无符号整数
int offset = data.Stride - rect.Width * 4;
for (int y = 0; y < rect.Height; y++)
{
if (direction == 0)
{
opacity = 1.0 * y / (rect.Height - 1);
}
else if (direction == 1)
{
opacity = 1 - 1.0 * y / (rect.Height - 1);
}
for (int x = 0; x < rect.Width; x++)
{
if (direction == 2)
{
opacity = 1.0 * x / (rect.Width - 1);
}
else if (direction == 3)
{
opacity = 1 - 1.0 * x / (rect.Width - 1);
}
p[3] = (byte)(p[3] * opacity);//对像素设置Alpha
p += 4;
} // x
p += offset;
} // y
}
bmp.UnlockBits(data);//从内存中解除锁定
return bmp;
}
效果图:
案例代码:把这些代码添加到Form里面,需要
using System.Drawing.Imaging;
以及允许不安全代码
[C#] 纯文本查看 复制代码 protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.BackColor = Color.Lime;
this.BackgroundImage = GradualAlpha(Image.FromFile("E:\\图片\\25011G41R3.jpg"), new Rectangle(30,150,300,100), 3);
}
/// <summary>
/// 渐变透明
/// </summary>
/// <param name="srcImage">原图</param>
/// <param name="rect">需要渐变处理的区域</param>
/// <param name="direction">渐变方向透明到不透明 0:上到下,1:下到上,2:左到右,3右到左</param>
/// <returns></returns>
public static Image GradualAlpha(Image srcImage, Rectangle rect, int direction)
{
Bitmap bmp = new Bitmap(srcImage);
double opacity = 1;//不透明度的百分比
//LockBits将Bitmap锁定到内存中
BitmapData data = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
unsafe
{
//p指向地址
byte* p = (byte*)data.Scan0;//8位无符号整数
int offset = data.Stride - rect.Width * 4;
for (int y = 0; y < rect.Height; y++)
{
if (direction == 0)
{
opacity = 1.0 * y / (rect.Height - 1);
}
else if (direction == 1)
{
opacity = 1 - 1.0 * y / (rect.Height - 1);
}
for (int x = 0; x < rect.Width; x++)
{
if (direction == 2)
{
opacity = 1.0 * x / (rect.Width - 1);
}
else if (direction == 3)
{
opacity = 1 - 1.0 * x / (rect.Width - 1);
}
p[3] = (byte)(p[3] * opacity);//对像素设置Alpha
p += 4;
} // x
p += offset;
} // y
}
bmp.UnlockBits(data);//从内存中解除锁定
return bmp;
}
运行效果图
|