diff --git a/src/Magpie.App/IconHelper.cpp b/src/Magpie.App/IconHelper.cpp index 17d265e1..6846241f 100644 --- a/src/Magpie.App/IconHelper.cpp +++ b/src/Magpie.App/IconHelper.cpp @@ -1,15 +1,14 @@ #include "pch.h" #include "IconHelper.h" #include "Logger.h" -#include "Utils.h" #include "Win32Utils.h" #include "StrUtils.h" +#include "CommonSharedConstants.h" using namespace winrt; using namespace Windows::Graphics::Imaging; using namespace Windows::UI::Xaml::Media::Imaging; - namespace winrt::Magpie::App { static bool CopyPixelsOfHBmp(HBITMAP hBmp, LONG width, LONG height, void* data) noexcept { @@ -92,11 +91,12 @@ static SoftwareBitmap HIcon2SoftwareBitmap(HICON hIcon) { for (uint32_t i = 0; i < pixelsSize; i += 4) { // hbmMask 表示是否应用掩码 - // 如果需要应用掩码而掩码不为零,那么这个图标无法转换为彩色图标,这种情况下直接忽略掩码 + // 如果需要应用掩码而掩码不为零,那么无损转换为彩色图标是不可能的,这里直接使用掩码作为颜色 if (maskData[i] != 0 && pixels[i] == 0 && pixels[i + 1] == 0 && pixels[i + 2] == 0) { // 掩码全为 0 表示透明像素 std::memset(pixels + i, 0, 4); } else { + // 无需应用掩码或掩码不为零 pixels[i + 3] = 255; } } @@ -261,4 +261,23 @@ SoftwareBitmap IconHelper::ExtractIconFromExe(const wchar_t* fileName, uint32_t return bitmap; } +SoftwareBitmap IconHelper::ExtractAppIcon(uint32_t preferredSize) { + // 作为性能优化,使用 LoadImage 而不是 SHDefExtractIcon 加载程序图标。 + // 经测试,LoadImage 快两倍左右。 + wil::unique_hicon hIcon((HICON)LoadImage( + GetModuleHandle(nullptr), + MAKEINTRESOURCE(CommonSharedConstants::IDI_APP), + IMAGE_ICON, + preferredSize, + preferredSize, + LR_DEFAULTCOLOR + )); + if (!hIcon) { + Logger::Get().Win32Error("提取程序图标失败"); + return nullptr; + } + + return HIcon2SoftwareBitmap(hIcon.get()); +} + } diff --git a/src/Magpie.App/IconHelper.h b/src/Magpie.App/IconHelper.h index 0aab3496..2c7048cd 100644 --- a/src/Magpie.App/IconHelper.h +++ b/src/Magpie.App/IconHelper.h @@ -4,8 +4,8 @@ namespace winrt::Magpie::App { struct IconHelper { static Windows::Graphics::Imaging::SoftwareBitmap ExtractIconFormWnd(HWND hWnd, uint32_t preferredSize, uint32_t dpi); - static Windows::Graphics::Imaging::SoftwareBitmap ExtractIconFromExe(const wchar_t* fileName, uint32_t preferredSize, uint32_t dpi); + static Windows::Graphics::Imaging::SoftwareBitmap ExtractAppIcon(uint32_t preferredSize); }; } diff --git a/src/Magpie.App/TitlebarControl.cpp b/src/Magpie.App/TitlebarControl.cpp index f1eb28d6..d55a5b58 100644 --- a/src/Magpie.App/TitlebarControl.cpp +++ b/src/Magpie.App/TitlebarControl.cpp @@ -17,8 +17,7 @@ TitleBarControl::TitleBarControl() { auto weakThis = that->get_weak(); SoftwareBitmapSource bitmap; - co_await bitmap.SetBitmapAsync(IconHelper::ExtractIconFromExe( - Win32Utils::GetExePath().c_str(), 40, USER_DEFAULT_SCREEN_DPI)); + co_await bitmap.SetBitmapAsync(IconHelper::ExtractAppIcon(40)); if (!weakThis.get()) { co_return;