1. 程式人生 > >unity之安卓手機截圖並顯示在相簿

unity之安卓手機截圖並顯示在相簿

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using UnityEngine.UI;

public class ScreenShot : MonoBehaviour {
    //截圖的相機
    public Camera camera1;

    public Image screenBg;

    //截圖縮小圖
    Sprite sprites;
    /// <summary>
    /// 截圖的按鈕事件
    /// </summary>
    public void CameraScreenShot()
    {
        //呼叫截圖方法
        CaptureCamera(camera1, new Rect(0,0,Screen.width,Screen.height));
        //呼叫給小截圖新增圖片
        AddImageToScreenKuang();
    }
    Texture2D CaptureCamera(Camera camera, Rect rect)
    {
        //獲取系統時間並命名相片名    
        DateTime now = DateTime.Now;
        string times = now.ToString();
        times = times.Trim();
        times = times.Replace(":", "");
        times = times.Replace("/", "");
        times = times.Remove(8,1);
        string filename = "/Screenshot" + times + ".png";

        // 建立一個RenderTexture物件  
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 16);
        // 臨時設定相關相機的targetTexture為rt, 並手動渲染相關相機  
        camera.targetTexture = rt;
        camera.Render();
        // 啟用這個rt, 並從中中讀取畫素。  
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        screenShot.ReadPixels(rect, 0, 0);// 注:這個時候,它是從RenderTexture.active中讀取畫素  
        screenShot.Apply();


        // 重置相關引數,以使用camera繼續在螢幕上顯示  
        camera.targetTexture = null;
        //ps: camera2.targetTexture = null;  
        RenderTexture.active = null; // JC: added to avoid errors  
        GameObject.Destroy(rt);
        // 最後將這些紋理資料,成一個png圖片檔案  
        byte[] bytes = screenShot.EncodeToPNG();
#if UNITY_EDITOR
        string Path_save = Application.streamingAssetsPath + filename;
        sprites = Sprite.Create(screenShot, new Rect(0, 0, screenShot.width, screenShot.height), new Vector2(0.5f, 0.5f));
#elif UNITY_ANDROID
        string destination = "/storage/emulated/0/DCIM/Camera";  
        //判斷目錄是否存在,不存在則會建立目錄    
        if (!Directory.Exists (destination)) {    
            Directory.CreateDirectory (destination);    
        }    
        string Path_save = destination+"/" + filename;  
        sprites = Sprite.Create(screenShot, new Rect(0, 0, screenShot.width, screenShot.height), new Vector2(0.5f, 0.5f));
#elif UNITY_IOS

#endif
        System.IO.File.WriteAllBytes(Path_save, bytes);
        Debug.Log(string.Format("截圖了一張照片: {0}", Path_save));

        return screenShot;
    }
    //新增截圖縮小圖
    void AddImageToScreenKuang()
    {
        screenBg.sprite = sprites;
        screenBg.gameObject.SetActive(true);
    }
    public void CancelClick()
    {
        screenBg.gameObject.SetActive(false);
    }
}