65.9K
CodeProject 正在变化。 阅读更多。
Home

可爱的金鱼桌面宠物(使用 alpha-PNG 和 GDI+)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.91/5 (224投票s)

2008 年 9 月 9 日

CPOL

1分钟阅读

viewsIcon

372583

downloadIcon

14816

使用 alpha-PNG 和 GDI+ 技术实现桌面宠物鱼!

GoldFish

引言

这篇文章演示了一个非常可爱的桌面金鱼宠物,使用了 Alpha-PNG 和 GDI+。这条可爱的小金鱼可以在你的桌面上游动,当你用鼠标尝试捕捉它时,它会试图逃脱。

背景

在我发布这些文章之后:一个酷炫的 Vista 侧边栏小工具风格的 CPU 信息动画控件!(已修复)一个酷炫的 Vista 侧边栏风格的时钟控件(4种样式)(已修复),很多人问我如何使用这些控件创建一个真正的 Alpha 透明窗体。现在,这已经成为现实!这是一个真正的 Alpha 透明窗体,带有动画效果,即使在一些非 Vista 操作系统(如 XP)中也能正常工作!

玩得开心!并且,别忘了投票!:)

使用代码

要使窗体透明,请使用以下代码将其背景设置为 Alpha 透明的 PNG 图片

public void SetBits(Bitmap bitmap)
{
    if (!haveHandle) return;
    if (!Bitmap.IsCanonicalPixelFormat(bitmap.PixelFormat) || 
        !Bitmap.IsAlphaPixelFormat(bitmap.PixelFormat))
        throw new ApplicationException("The picture must be " + 
                  "32bit picture with alpha channel");
    IntPtr oldBits = IntPtr.Zero;
    IntPtr screenDC = Win32.GetDC(IntPtr.Zero);
    IntPtr hBitmap = IntPtr.Zero;
    IntPtr memDc = Win32.CreateCompatibleDC(screenDC);
    try
    {
        Win32.Point topLoc = new Win32.Point(Left, Top);
        Win32.Size bitMapSize = new Win32.Size(bitmap.Width, bitmap.Height);
        Win32.BLENDFUNCTION blendFunc = new Win32.BLENDFUNCTION();
        Win32.Point srcLoc = new Win32.Point(0, 0);
        hBitmap = bitmap.GetHbitmap(Color.FromArgb(0));
        oldBits = Win32.SelectObject(memDc, hBitmap);
        blendFunc.BlendOp = Win32.AC_SRC_OVER;
        blendFunc.SourceConstantAlpha = 255;
        blendFunc.AlphaFormat = Win32.AC_SRC_ALPHA;
        blendFunc.BlendFlags = 0;
        Win32.UpdateLayeredWindow(Handle, screenDC, ref topLoc, ref bitMapSize, 
                         memDc, ref srcLoc, 0, ref blendFunc, Win32.ULW_ALPHA);
    }
    finally
    {
        if (hBitmap != IntPtr.Zero)
        {
            Win32.SelectObject(memDc, oldBits);
            Win32.DeleteObject(hBitmap);
        }
        Win32.ReleaseDC(IntPtr.Zero, screenDC);
        Win32.DeleteDC(memDc);
    }
}

很简单吧!现在,你可以使用计时器控件来实现动画功能。

抱歉我的英语不好!请查看源代码以获取更多详细信息。

关注点

  • 使用 GDI+ 和 C# 进行开发是一件非常有趣的事情!
  • PNG 格式非常适合绘制 Alpha 图片!
  • 更多代码示例,请访问 我的个人网站

历史

© . All rights reserved.