APSchmidt 发表于 2022-4-27 21:50

UE Slate样式

先说明一下,这个是因为写插件的时候需要用到的,项目中如果有需要的话,也可以参考!


前提

在Module要使用Style之前,我们就已经需要对style进行注册!
void FMyEditorModule::StartupModule()
{
    // 创建style
    FMyEditorStyle::Initialize();
    ...
}
还有在Module销毁的时候记得清理一下
void FMyEditorModule::ShutdownModule()
{
    FMyEditorStyle::Shutdown();
}
注册style

为了防止多次生成一些对象,我这里使用了静态
TSharedPtr< FSlateStyleSet > FMyEditorStyle::StyleInstance = nullptr;

void FMyEditorStyle::Initialize()
{
    if (!StyleInstance.IsValid())
    {
      StyleInstance = Create();
      FSlateStyleRegistry::RegisterSlateStyle(*StyleInstance);
    }
}
FSlateStyleRegistry::RegisterSlateStyle可以将已经处理好的style添加到全局的slatestyle中,以方便我们在代码中使用;
TSharedRef< FSlateStyleSet > FMyEditorStyle::Create()
{
    // "MyEditor"是这个style的名称,如果要使用的时候需要记住这个名称,可以提取成成员方法,我偷懒,就不说了
    TSharedRef< FSlateStyleSet > style = MakeShareable(new FSlateStyleSet("MyEditor"));
    style->SetContentRoot(IPluginManager::Get().FindPlugin(TEXT("MyEditor"))->GetBaseDir() / TEXT("Resources"));
    style->Set("MyEditor.MenuIcon", new FSlateImageBrush(style->RootToContentDir("Button_Icon40", TEXT(".png")), FVector2D(128,128)));
    return style;
}
IPluginManager的使用需要在Build.cs中添加DependencyModuleNames.Add Projects;
style->SetContentRoot是设置相对目录的!
style->Set是可以绑定相关的样式的


demo代码中,我使用的是图片



FSlateImageBrush
中设置的大小可以和资源的真实大小无关,但是该大小会同步影响了菜单的大小,文章头的诡异就是因为我设置成了 https://www.zhihu.com/equation?tex=128 了,最好的大小是 https://www.zhihu.com/equation?tex=40 ;

简单使用

    ToolBarBuilder.AddComboButton(
      FUIAction(),
      FOnGetContent::CreateRaw(this, &FMyEditorModule::AddToolsSubMenu),
      LOCTEXT("MyTools", "My Tools"),
      LOCTEXT("MyToolsTips", "My Tools Tips"),
      FSlateIcon(TEXT("MyEditor"), TEXT("MyEditor.MenuIcon"))
    );
只需要简单在FSlateIcon中传入style的名称和对应的key就可以了!
销毁

清理引用就行了!
void FMyEditorStyle::Shutdown()
{
    FSlateStyleRegistry::UnRegisterSlateStyle(*StyleInstance);
    ensure(StyleInstance.IsUnique());
    StyleInstance.Reset();
}
页: [1]
查看完整版本: UE Slate样式