欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity 截图并将图片保存到手机指定文件夹

程序员文章站 2024-01-13 14:49:22
...

Unity版本:5.6

在使用下面代码前,你一定要设置如下,否则就不起作用了

Unity 截图并将图片保存到手机指定文件夹

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.IO;
 
public class jie_tu1 : MonoBehaviour {
 
    public Text log;
 
    public void jietu()
    {
        //获取系统时间并命名相片名  
        System.DateTime now = System.DateTime.Now;
        string times = now.ToString();
        times = times.Trim();
        times = times.Replace("/", "-");
        string filename = "Screenshot" + times + ".png";
 
        //判断是否为Android平台  
        if (Application.platform == RuntimePlatform.Android)
        {
            //截取屏幕  
            Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
            texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
            texture.Apply();
 
            //转为字节数组  
            byte[] bytes = texture.EncodeToPNG();
 
            string destination = "/sdcard/DCIM/截图";
 
            //判断目录是否存在,不存在则会创建目录  
            if (!Directory.Exists(destination))
            {
                Directory.CreateDirectory(destination);
            }
 
            string Path_save = destination + "/" + filename;//filename 是图片名
 
            //保存图片  
            System.IO.File.WriteAllBytes(Path_save, bytes);
            log.text = destination; //输出一下路径
        }
    }
}

 

相关标签: Unity

上一篇: Mysql_innodb行锁检测

下一篇: