主要思路通过RT截图,拷贝到一个Texture2D 上,新建一个材质球用Unlit_YellowFilterShader,改变_GrayAmount参数达到效果
//屏幕截图泛黄滤镜
public static void SetTextureShotFilter(Transform tf_, float duration_, LuaFunction func_)
{
Camera camera = CameraMgr.Instance.MainCamera;
float current_width = UIHelper.GetNGUIScreenWidth();
float current_height = UIHelper.GetNGUIScreenHeight();
UnityEngine.Rect rect = new Rect(current_width * 0f, current_height * 0f, current_width * 1f, current_height * 1f);
// 创建一个RenderTexture对象
RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 16);
// 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
camera.targetTexture = rt;
camera.Render();
// 激活这个rt, 并从中中读取像素。
RenderTexture.active = rt;
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGBA32, false);
screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
screenShot.Apply();
// 重置相关参数,以使用camera继续在屏幕上显示
camera.targetTexture = null;
//ps: camera2.targetTexture = null;
RenderTexture.active = null; // JC: added to avoid errors
GameObject.Destroy(rt);
OperaMgr.Instance.CreateYellowFilter(tf_, screenShot, duration_, () =>
{
if (func_ != null)
{
func_.Call();
}
});
}
Shader代码:
Shader "Ygame/Unlit/Unlit_YellowFilter"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_GrayAmount("GrayAmount", Range(-2.0, 3.0)) = 0
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
fixed4 color : COLOR;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float _GrayAmount;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : COLOR
{
// sample the texture
fixed4 col = tex2D(_MainTex, i.uv);
float grey = dot(col.rgb, float3(0.299, 0.587, 0.114));
col.rgb = lerp(col.rgb, float3(grey, grey, grey), _GrayAmount);
float3 filter = lerp(float3(1,1,1), float3(251.0 / 256, 220.0 / 256, 189.0 / 256), _GrayAmount);
col.rgb = (col.rgb * filter);
return col;
}
ENDCG
}
}
}