- 前言
UE4常用的new FSlateBrush的方式与正常的SlateStyle的方式就不说了,这类的文章很多,这里主要仿照引擎源码加载图片的方式加加载
参考源码:FTestStyle
.h
class FMainStyle
{
public:
static TSharedRef< class ISlateStyle > Create();
static const ISlateStyle& Get()
{
return *( Instance.Get() );
}
static void ResetToDefault()
{
SetStyle( FMainStyle::Create() );
}
private:
static void SetStyle( const TSharedRef< class ISlateStyle >& NewStyle )
{
if ( Instance.IsValid() )
{
FSlateStyleRegistry::UnRegisterSlateStyle( *Instance.Get() );
}
Instance = NewStyle;
if ( Instance.IsValid() )
{
FSlateStyleRegistry::RegisterSlateStyle( *Instance.Get() );
}
else
{
ResetToDefault();
}
}
private:
/** Singleton instances of this style. */
static TSharedPtr< class ISlateStyle > Instance;
};
.cpp
#define IMAGE_BRUSH( RelativePath, ... ) FSlateImageBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BOX_BRUSH( RelativePath, ... ) FSlateBoxBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BORDER_BRUSH( RelativePath, ... ) FSlateBorderBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define DEFAULT_FONT(...) FCoreStyle::GetDefaultFontStyle(__VA_ARGS__)
TSharedPtr< ISlateStyle > FMainStyle::Instance = nullptr;
TSharedRef<ISlateStyle> FMainStyle::Create()
{
TSharedRef< FSlateStyleSet > Style = MakeShareable( new FSlateStyleSet("MainStyle") );
Style->SetContentRoot( FPaths::ProjectContentDir() / TEXT("Textures") );
FVector2D BackGroundSize(400, 400);
Style->Set( "BackGround", new IMAGE_BRUSH( "CheckBox_Checked", BackGroundSize ) );
return Style;
}
初始化:
FMainStyle::ResetToDefault();
获取Brush:
SAssignNew(BackGroundImage, SImage)
.Image(FMainStyle::Get().GetBrush("BackGround"))
图片资源放在自己定义的路径下面,比如我这是://Style->SetContentRoot( FPaths::ProjectContentDir() / TEXT("Textures") );
注意:这里不需要把图片导入引擎,直接放在对应路径使用的,所以,如果用这种方式,打包一定要包含路径,记得规范开发流程