Unity 圖片鏡像翻轉Shader


通過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();

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM