Unity3D指定相机截屏并存储在手机相册中(安卓)

最近公司项目里需要截屏的功能,在网上找了好久,都没有合适的解决方法,有些方法已经不能用了,但是也给我提供了一些思路,通过一段时间的研究,解决了这个问题,现在和大家一起分享一下。
//下面是代码,可以直接用

public class Screenshots : MonoBehaviour {

 //这个相机是用来截屏的,相机的Claer Flags 的属性选择为Depth Only 
public Camera CameraTrans;
private Texture2D mTexture1;
private string mPath;
public GameObject picture;
private string mingming;


// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}
/// 
/// 开启相机
/// 

public void screenshot()
{
    //用时间命名
   string mingming= System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day + System.DateTime.Now.Hour + System.DateTime.Now.Minute + System.DateTime.Now.Second;
    //平台判断
    if (Application.platform == RuntimePlatform.Android)
    {    
        //安卓设备的相册路径
        mPath = "/sdcard/DCIM/Camera/" + mingming + ".jpg";

    }else if (Application.platform == RuntimePlatform.WindowsEditor)
    {
        mPath = Application.dataPath + "\\Resources\\" + mingming + ".jpg";
    }
    StartCoroutine(CaptureByCamera(CameraTrans, new Rect(0, 0, 1024, 768), mPath));

}
private IEnumerator CaptureByCamera(Camera mCamera, Rect mRect, string mFileName)
{
    //等待渲染线程结束  
    yield return new WaitForEndOfFrame();

    //初始化RenderTexture  
    RenderTexture mRender = new RenderTexture((int)mRect.width, (int)mRect.height, 0);
    //设置相机的渲染目标  
    mCamera.targetTexture = mRender;
    //开始渲染  
    mCamera.Render();

    //激活渲染贴图读取信息  
    RenderTexture.active = mRender;

    Texture2D mTexture = new Texture2D((int)mRect.width, (int)mRect.height, TextureFormat.RGB24, false);
    //读取屏幕像素信息并存储为纹理数据  
    mTexture.ReadPixels(mRect, 0, 0);
    //应用  
    mTexture.Apply();

    //释放相机,销毁渲染贴图  
    mCamera.targetTexture = null;
    RenderTexture.active = null;
    GameObject.Destroy(mRender);

    //将图片信息编码为字节信息  
    byte[] bytes = mTexture.EncodeToPNG();

    //保存  
        File.WriteAllBytes(mFileName, bytes);
    //将纹理图存在静态类里
    mTexture1 = mTexture;
    picture.GetComponent().sprite = Sprite.Create(mTexture1, new Rect(0, 0, 1024, 768), new Vector2(Screen.height / 2, Screen.width / 2));
    //如果需要可以返回截图  
    //return mTexture;  

}

}

Unity3D指定相机截屏并存储在手机相册中(安卓)_第1张图片

这样你就可以在进行用了,但是如果要打包APK ,你还要进行一些设置

Unity3D指定相机截屏并存储在手机相册中(安卓)_第2张图片

你可能感兴趣的:(Vuforia)