Slate中动态加载本地图片

来源:互联网 发布:水晶淘宝店店铺介绍 编辑:程序博客网 时间:2024/04/28 23:53

概述

yo!yo!yo!各位兄弟姐妹,七夕过的好吗,昨晚我在研究,今天终于搞定。yo!this’s my freestyle。动态加载图片,就是这么简单。
下面将使用到,GameMode,SImage,FSlateBrush

实现

总的来说是参考UMG的实现思路。需要添加的模块,头文件引用,请自行添加。

1.UMG中的方法

要在Slate中实现动态加载图片,可以学习UMG中的加载图片。在UMG中可以找到SetBrushResourceToTexture(),找到它的定义,在UWidgetBlueprintLibrary

/** Sets the resource on a brush to be a UTexture2D. */UFUNCTION(BlueprintCallable, Category="Widget|Brush")static void SetBrushResourceToTexture(UPARAM(ref) FSlateBrush& Brush, UTexture2D* Texture);
void UWidgetBlueprintLibrary::SetBrushResourceToTexture(FSlateBrush& Brush, UTexture2D* Texture){    Brush.SetResourceObject(Texture);}

2.Slate中显示图片的控件

在Slate显示图片的控件是SImage,其中有个SetImage方法,需要理解真正保存图片资源的是FSlateBrush

/** See the Image attribute */void SetImage(TAttribute<const FSlateBrush*> InImage);

3.实现动态加载

接下来,在一个新项目的AFirstDemoGameMode中,写测试逻辑。

//FirstDemoGameMode.h//...#include "SImage.h"//...UCLASS(minimalapi)class AFirstDemoGameMode : public AGameModeBase{    GENERATED_BODY()//.....public:    FSlateBrush TempBrush;    TSharedPtr<SImage> SImagePtr;    UTexture2D* NewTexture;//.....}
//FirstDemoGameMode.cpp//某方法{    // 在游戏内添加一个图片    GEngine->GameViewport->AddViewportWidgetContent(        SAssignNew(SImagePtr, SImage));    // 从本地磁盘读取图片,此方法不是UE4的API,网上有很多种实现,请自己去查    NewTexture = LoadImageFileToTexture2D(TEXT("E:/123/test.png"));    // 设置新图片资源    TempBrush.SetResourceObject(Texture);    SImagePtr->SetImage(&tempBrush);}

补充1:为什么不用UWidgetBlueprintLibrary库

因为项目是纯Slate,要用UWidgetBlueprintLibrary库需要引用UMG模块,所以手动把库中的实现提出来。

补充2:引起死循环的错误写法

{    // 在游戏内添加一个图片    GEngine->GameViewport->AddViewportWidgetContent(        SAssignNew(SImagePtr, SImage));    // 从本地磁盘读取图片,此方法不是UE4的API,网上有很多种实现,请自己去查    NewTexture = LoadImageFileToTexture2D(TEXT("E:/123/test.png"));    // 设置新图片资源,这里使用临时的FSlateBrush变量,会引起死循环。    FSlateBrush newTempBrush = FSlateBrush();    newTempBrush.SetResourceObject(Texture);    SImagePtr->SetImage(&newTempBrush);}