Unity3D编写脚本从屏幕截取一个子区域保存为Texture2D,用于保存图片和当贴图都可以

GameObject UserCutBox;  // 用于描述截取范围
Texture2D fullscreenCapture ;
Texture2D subarea;
void Start()
    {
        rcttrans = GameObject.Find("UserCutBox").GetComponent();
    }

// 开始j截取屏幕(全屏)
public void startSnapShotFullScreen()
    {
        StartCoroutine(CaptureFullScreenData(OnCaptureFullEnd));
    }

private IEnumerator CaptureFullScreenData(Action onEnd=null)
    {
        yield return new WaitForEndOfFrame();
        Texture2D texture = ScreenCapture.CaptureScreenshotAsTexture();
        onEnd?.Invoke(texture);
    }
// 全屏截图结束的回调
public void OnCaptureFullEnd(object data)
    {
        // 保存全屏截屏
        fullscreenCapture = (Texture2D)data;

        // 开始身体截屏
        StartCoroutine(CaptureByRect(new Rect(rcttrans.offsetMin, rcttrans.offsetMax - rcttrans.offsetMin), OnCaptureSubAreaEnd));
    }

// 根据一个Rect类型来截取指定范围的屏幕  
private IEnumerator CaptureByRect(Rect mRect, Action onend=null)
    {
        //等待渲染线程结束  
        yield return new WaitForEndOfFrame();

        //初始化Texture2D  
        Texture2D mTexture = new Texture2D((int)mRect.width, (int)mRect.height, TextureFormat.RGB24, false);

        //读取屏幕像素信息并存储为纹理数据  
        mTexture.ReadPixels(mRect, 0, 0);
        mTexture.Apply();

        onend(mTexture);
    }

// 子区域截屏结束
public void OnCaptureSubAreaEnd(object data)
{
    subarea = (Texture2D)data;
}
 
  

 

你可能感兴趣的:(Unity3D编写脚本从屏幕截取一个子区域保存为Texture2D,用于保存图片和当贴图都可以)