在Unity中,屏幕后处理MonoBehaiver.OnRenderImage(RenderImage source,RenderImage destination)可以把屏幕上的渲染出来的图像传入到source中,再经过Graphics.Blit(source,destination,mat)方法指定一个材质处理后再渲染出来。
//脚本,挂载到Camera的物体上 using UnityEngine; public class ImageChuliXia : MonoBehaviour { public Shader shader; //具体处理的Shader [Range(0, 3)] public float MingLiang = 1.5f;//明亮度 [Range(0, 3)] public float BaoHe = 1.5f;//饱和度 [Range(0, 3)] public float DuiBi = 1.5f;//对比度 private Material mat; private void OnRenderImage(RenderTexture source, RenderTexture destination) { if (shader == null) { Graphics.Blit(source, destination); return; } if (mat == null) { mat = new Material(shader);//动态创建一个材质 mat.hideFlags = HideFlags.DontSave; } mat.SetFloat("_Mingliang", MingLiang); mat.SetFloat("_Baohe", BaoHe); mat.SetFloat("_Duibi", DuiBi); Graphics.Blit(source,destination, mat);//直接调用方法,让mat处理一番 } }
//Shader处理 Shader "Unlit/ImageChuliXia" { Properties { _MainTex ("Texture", 2D) = "white" {} //这里会传入source _Mingliang("_Mingliang",Float) = 1.5 //材质设置进来 _Baohe("_Baohe",Float) = 1.5 _Duibi("_Duibi",Float) = 1.5 } SubShader { Tags { "RenderType"="Opaque" } LOD 100 Pass { ZTest Always Cull Off ZWrite Off CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct v2f { float2 uv : TEXCOORD0; float4 vertex : SV_POSITION; }; sampler2D _MainTex; float4 _MainTex_ST; float _Mingliang;//明亮度值 float _Baohe;//饱和度值 float _Duibi;//对比度值 v2f vert (appdata_img v) //使用的内置的appdata_img { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.uv = v.texcoord; return o; } fixed4 frag (v2f i) : SV_Target { fixed4 renderTex = tex2D(_MainTex, i.uv); //明亮度 fixed3 AllColor = renderTex.rgb * _Mingliang; //直接相乘就好了 //饱和度 //fixed lum = Luminance(renderTex.rgb); //计算当前颜色的亮度值 fixed lum = 0.2125 * renderTex.r + 0.7154 * renderTex.g + 0.0721 * renderTex.b; fixed3 lumColor = fixed3(lum, lum, lum);//构建一个为0的饱和度 AllColor = lerp(lumColor,AllColor, _Baohe); //对比度 fixed3 avgColor = fixed3(0.5, 0.5, 0.5);//构建一个为0的对比度 AllColor = lerp(avgColor, AllColor, _Duibi); return fixed4(AllColor,renderTex.a); } ENDCG } } Fallback Off }
appdata_img只包含图像处理时必需的顶点坐标和纹理坐标等变量。