如何渲染透明光标到位图保留alpha通道?

Mur*_*are 9 .net c# transparency gdi+ cursor

我使用下面的代码渲染透明图标:

    private void button1_Click(object sender, EventArgs e)
    {
        // using LoadCursorFromFile from user32.dll
        var cursor = NativeMethods.LoadCustomCursor(@"d:\Temp\Cursors\Cursors\aero_busy.ani");

        // cursor -> bitmap
        Bitmap bitmap = new Bitmap(48, 48, PixelFormat.Format32bppArgb);
        Graphics gBitmap = Graphics.FromImage(bitmap);
        cursor.DrawStretched(gBitmap, new Rectangle(0, 0, 32, 32));

        // 1. Draw bitmap on a form canvas
        Graphics gForm = Graphics.FromHwnd(this.Handle);
        gForm.DrawImage(bitmap, 50, 50);

        // 2. Draw cursor directly to a form canvas
        cursor.Draw(gForm, new Rectangle(100, 50, 32, 32));

        cursor.Dispose();
    }
Run Code Online (Sandbox Code Playgroud)

不幸的是我无法将透明光标渲染到位图!当我将Cursor直接绘制到窗体画布时,它可以工作,但是当我将Cursor绘制到位图时会出现问题.任何建议都非常感谢.

替代文字

Cod*_*ray 9

您现在拥有的解决方案并不完全适用于托管代码.你自己的评论说你是LoadCursorFromFile来自user32.dll的P/Invoking .无论如何,使用Win32 API实际上并不是你应该害怕的.

正如我在评论中提到的,您尝试做的事情通常是使用GDI +绘图函数存在问题,就像.NET Framework提供的大多数函数一样.使用GDI可以更轻松地完成任务.您可以使用以下代码从光标(或图标,它们基本上可以互换)创建一个尊重Alpha通道的位图:

[StructLayout(LayoutKind.Sequential)]    
private struct ICONINFO
{
    public bool fIcon;
    public int xHotspot;
    public int yHotspot;
    public IntPtr hbmMask;
    public IntPtr hbmColor;
}

[DllImport("user32")]
private static extern bool GetIconInfo(IntPtr hIcon, out ICONINFO pIconInfo);

[DllImport("user32.dll")]
private static extern IntPtr LoadCursorFromFile(string lpFileName);

[DllImport("gdi32.dll", SetLastError = true)]
private static extern bool DeleteObject(IntPtr hObject);

private Bitmap BitmapFromCursor(Cursor cur)
{
    ICONINFO ii;
    GetIconInfo(cur.Handle, out ii);

    Bitmap bmp = Bitmap.FromHbitmap(ii.hbmColor);
    DeleteObject(ii.hbmColor);
    DeleteObject(ii.hbmMask);

    BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);
    Bitmap dstBitmap = new Bitmap(bmData.Width, bmData.Height, bmData.Stride, PixelFormat.Format32bppArgb, bmData.Scan0);
    bmp.UnlockBits(bmData);

    return new Bitmap(dstBitmap);
}

private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
    //Using LoadCursorFromFile from user32.dll, get a handle to the icon
    IntPtr hCursor = LoadCursorFromFile("C:\\Windows\\Cursors\\Windows Aero\\aero_busy.ani");

    //Create a Cursor object from that handle
    Cursor cursor = new Cursor(hCursor);

    //Convert that cursor into a bitmap
    using (Bitmap cursorBitmap = BitmapFromCursor(cursor))
    {
        //Draw that cursor bitmap directly to the form canvas
        e.Graphics.DrawImage(cursorBitmap, 50, 50);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果此代码不能编译,请确保您添加using语句System.Drawing,System.Drawing.ImagingSystem.Runtime.InteropServices.还记得将该Form1_Paint方法连接为表单Paint事件的处理程序.

经过测试可以工作:

光标,从位图中完成,带有alpha通道