Skip to content

Commit

Permalink
perf: 优化加载标题栏图标的性能
Browse files Browse the repository at this point in the history
  • Loading branch information
Blinue committed Jun 26, 2024
1 parent bb9772a commit 37fc706
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
25 changes: 22 additions & 3 deletions src/Magpie.App/IconHelper.cpp
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -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());
}

}
2 changes: 1 addition & 1 deletion src/Magpie.App/IconHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
};

}
3 changes: 1 addition & 2 deletions src/Magpie.App/TitlebarControl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 37fc706

Please sign in to comment.