准备一个模糊Shader
将相机视图渲染到texture上
将渲染后的texture赋值给RawImage图片
using UnityEngine;
using UnityEngine.UI;
public class UIBgBlur : MonoBehaviour
{
// Start is called before the first frame update
private RawImage blur;
private Camera uiCamera;
private Canvas blurCanvas;
void Start()
{
blur = transform.Find("RawImage").GetComponent<RawImage>();
uiCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
blurCanvas = GetComponent<Canvas>();
}
public void SetSortingOrder(int order)
{
blurCanvas.overrideSorting = true;
blurCanvas.sortingOrder = order;
}
public void Show()
{
DrawCameraPicture();
}
private void DrawCameraPicture()
{
// 抓取相机视图转为图片
RenderTexture targetTexture = new RenderTexture(Screen.width, Screen.height, 24, RenderTextureFormat.ARGB32);
var texRect = new Rect(0, 0, targetTexture.width, targetTexture.height);
targetTexture.name = "UIBgBlur_onSceneMemory";
var tempTexture2D = new Texture2D(targetTexture.width, targetTexture.height, TextureFormat.RGB24, false);
tempTexture2D.name = "UIBgBlur_onSceneMemory";
var cameraPrevT = uiCamera.targetTexture;
uiCamera.targetTexture = targetTexture; // 设置相机的目标渲染纹理。
uiCamera.Render(); // 手动渲染相机
uiCamera.targetTexture = cameraPrevT; // 还原相机渲染目标
RenderTexture.active = targetTexture; // 设置当前活动的渲染纹理
tempTexture2D.ReadPixels(texRect, 0, 0);
tempTexture2D.Apply();
RenderTexture.active = null; // 清空
// 赋值给RawImage
blur.texture = tempTexture2D;
blur.texture.name = "UIBgBlur_onSceneMemory";
blur.gameObject.SetActive(true);
}
}