본문 바로가기
Unity3D/Unity & C#

Unity & C# ~ Crop Image

by 캬캬백곰 2022. 10. 7.
728x90
using System.Collections;
using System.Collections.Generic;

using UnityEngine;
using UnityEngine.UI;

public class TestCropTexture : MonoBehaviour
{
    public Texture2D sourceImg; // 소스 이미지
    public Image img;           // Image UGUI

    // Start is called before the first frame update
    void Start()
    {
        TestCrop();
    }

    void TestCrop()
    {
        var tex = sourceImg.GetRawTextureData(); // 소스 이미지 텍스쳐 RAW DATA 변환

        // 소스 이미지 texture -> texture2d
        Texture2D tex2d = new Texture2D(sourceImg.width, sourceImg.height, sourceImg.format, false);
        tex2d.LoadRawTextureData(tex);
        tex2d.Apply();

        // crop size
        int cropWidth = 500;
        int cropHeight = 500;

        // original image size
        int sourceWidth = tex2d.width;
        int sourceHeight = tex2d.height;

        var tex2 = new Texture2D(cropHeight, cropHeight);
        //tex2.SetPixels(tex2d.GetPixels(0, 0, cropWidth, cropHeight));
        tex2.SetPixels(tex2d.GetPixels(Mathf.FloorToInt((sourceWidth - cropWidth) * 0.5f), Mathf.FloorToInt((sourceHeight - cropHeight) * 0.5f), cropWidth, cropHeight));
        tex2.Apply();

        img.sprite = Sprite.Create(tex2, Rect.MinMaxRect(0, 0, tex2.width, tex2.height), new Vector2(0.5f, 0.5f));
    }
}

crop image axis

728x90
반응형