通过shader将照片水平、垂直方向镜像翻转,比通过Texture2D逐像素操作快多了
Shader "Unlit/Mirror" { Properties { _MainTex ("Texture", 2D) = "white" {} _MirrorU("水平镜像翻转",float)=0 _MirrorV("竖直镜像翻转",float)=0 } SubShader { Tags {"RenderType" = "Opaque" "Queue" = "Geometry"} Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag sampler2D _MainTex; float _MirrorU; float _MirrorV; struct a2v{ float4 vertex : POSITION; float3 texcoord : TEXCOORD0; }; struct v2f{ float4 pos : SV_POSITION; float2 uv : TEXCOORD0; }; v2f vert(a2v v){ v2f o; o.pos = UnityObjectToClipPos(v.vertex); o.uv = v.texcoord; if(_MirrorU>0){ o.uv.x = 1 - o.uv.x;//Flip the coordinates to get the image sampling data } if(_MirrorV>0){ o.uv.y = 1 - o.uv.y;//Flip the coordinates to get the image sampling data } return o; } fixed4 frag(v2f i) : SV_Target{ return tex2D(_MainTex,i.uv); } ENDCG } } FallBack off }
C#代码这样调用
Material mirror;//用于水平镜像翻转的shader /// <summary> /// 镜像翻转 /// </summary> /// <returns></returns> public RenderTexture Mirror(Texture tex, bool isMirrorU, bool isMirrorV) { RenderTexture rt = RenderTexture.GetTemporary(tex.width, tex.height, 0, RenderTextureFormat.ARGB32); mirror.SetFloat("_MirrorU", isMirrorU ? 1 : 0);//是否水平镜像翻转 mirror.SetInt("_MirrorV", isMirrorV ? 1 : 0);//是否竖直镜像翻转 Graphics.Blit(tex, rt, mirror); return rt; }
保存shader处理过的图片
Texture2D t2 = new Texture2D(rt.width, rt.height); t2.ReadPixels(new UnityEngine.Rect(0, 0, rt.width, rt.height), 0, 0); t2.Apply();