Unity Texture2D 회전

Roh·2023년 12월 3일

Unity에서 Texture2D Rotate를 해보자.

내가 사용하는 갤럭시 탭 셀프 카메라가 상단 중앙이 아닌 중단 우측에 달려있어. 사진이 다 가로로 찍히는 문제가 있었다. 이 가로 사진을 세로 사진으로 회전시켜야 하는데 마땅한 reference가 없어 글을 작성하게 됐다.

아래와 같이 rotateTexture 함수를 구현했다.

public static Texture2D RotateImage(Texture2D tex, float angleDegrees)
    {
        int originalWidth = tex.width;
        int originalHeight = tex.height;

        // 90도 또는 270도 회전 시, 너비와 높이가 바뀜
        int width = angleDegrees == 90 || angleDegrees == 270 ? originalHeight : originalWidth;
        int height = angleDegrees == 90 || angleDegrees == 270 ? originalWidth : originalHeight;

        Texture2D rotatedTex = new Texture2D(width, height, tex.format, false);

        float halfOriginalWidth = originalWidth * 0.5f;
        float halfOriginalHeight = originalHeight * 0.5f;
        float halfWidth = width * 0.5f;
        float halfHeight = height * 0.5f;

        float phi = Mathf.Deg2Rad * angleDegrees;
        float cosPhi = Mathf.Cos(phi);
        float sinPhi = Mathf.Sin(phi);

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                float cX = x - halfWidth;
                float cY = y - halfHeight;
                int originalX = Mathf.RoundToInt(cosPhi * cX - sinPhi * cY + halfOriginalWidth);
                int originalY = Mathf.RoundToInt(sinPhi * cX + cosPhi * cY + halfOriginalHeight);

                bool insideOriginalBounds = (originalX >= 0 && originalX < originalWidth) &&
                                            (originalY >= 0 && originalY < originalHeight);

                rotatedTex.SetPixel(x, y, insideOriginalBounds ? tex.GetPixel(originalX, originalY) : new Color(0, 0, 0, 0));
            }
        }

        rotatedTex.Apply();
        return rotatedTex;
    }

정상적으로 작동했당.

before

after

하지만 2중 for문으로 가로 세로 전체 픽셀을 바꾸다 보니 시간이 오래 걸린다. 2초 정도 소요되는데, 나중에 기회가 된다면 속도를 개선해봐야겠다.

***Reference
https://gamedev.stackexchange.com/questions/203539/rotating-a-unity-texture2d-90-180-degrees-without-using-getpixels32-or-setpixels

profile
Better than doing nothing

0개의 댓글