Unity 翻转Texture2D (包含Readable=false)

Unity 翻转Texture2D 包含Readable=false

		/// <summary>
        /// 翻转贴图
        /// </summary>
        /// <param name="origin"></param>
        /// <returns></returns>
        public static Texture2D InverseTex(this Texture2D origin, bool isInverseV = true)
        {
    
    
            Texture2D newTex = new Texture2D(width: origin.width, height: origin.height, textureFormat: origin.format, mipChain: false, linear: true);
            newTex.name = origin.name;
            //原图片只读模式需要使用RenderTexture进行拷贝
            if (origin.isReadable == false)
            {
    
    
                newTex.FillPixelsFromReadOnlyTex(origin: origin);
                origin = newTex;
            }

            //翻转
            Color[] colors = new Color[origin.height * origin.height];
            for (int row = 0; row < origin.height; row++)
            {
    
    
                for (int col = 0; col < origin.width; col++)
                {
    
    
                    int index = row * origin.width + col;
                    int x = isInverseV == true ? col : origin.width - 1 - col;
                    int y = isInverseV == true ? origin.height - 1 - row : row;
                    colors[index] = origin.GetPixel(x: x, y: y);
                }
            }
            newTex.SetPixels(colors: colors);
            newTex.Apply();
            string msg = isInverseV == true ? "V方向" : "U方向";
            Debug.Log($"{
      
      msg}翻转贴图:{
      
      origin.name}");
            return newTex;
        }
		/// <summary>
        /// 从不可读贴图中提取像素
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="dest"></param>
        public static void FillPixelsFromReadOnlyTex(this Texture2D dest, Texture2D origin)
        {
    
    
            var destRenderTexture = RenderTexture.GetTemporary(width: origin.width, height: origin.height, depthBuffer: 0, format: RenderTextureFormat.ARGB32, readWrite: RenderTextureReadWrite.Linear);
            Graphics.Blit(origin, destRenderTexture);
            dest.ReadPixels(new Rect(0, 0, destRenderTexture.width, destRenderTexture.height), 0, 0);
            dest.Apply();
            Debug.Log($"从不可读贴图:{
      
      origin.name}中提取像素");
        }

猜你喜欢

转载自blog.csdn.net/qq_26318597/article/details/127538964
今日推荐