ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Unity安卓截图分享(一)

2021-12-15 19:01:33  阅读:222  来源: 互联网

标签:截图 string 安卓 tex Unity new using


Unity安卓截图分享功能(一):截图

目前掌握的Unity在安卓的截图有两种,一个是安卓自带截图(操作简单,功能有局限性),另一中Texture2D转二进制截图(稍微麻烦,自由度高)。(附完整代码)

Unity自带API截图

将程序运行中的某一帧的画面截取下来。
代码如下

ScreenCapture.CaptureScreenshot(Application.persistentDataPath + "/ScreenShoot.png");

Texture2D截图

简单代码如下

Texture2D tex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, true);
        yield return new WaitForEndOfFrame();
        tex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, true);
        tex.Apply();
        yield return tex;
        byte[] byt = tex.EncodeToPNG();

将屏幕截图以二进制形式保存在字节数组中,将二进制数组保存至文件中。

保存至文件

Android系统在10.0版本之后更新了文件权限方法,在截图前先向手机获取文件的读写权限,因此需要添加一些配置和代码才能获取文件权限。

代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Android;

public static class AndroidPermissionMgr
{
    /// <summary>
    /// 外部访问方法
    /// </summary>
    /// <param name="type">权限名</param>
    /// <param name="time">如拒绝延迟多久再次申请</param>
    public static void Get(string type, float time)
    {
        if (!Permission.HasUserAuthorizedPermission(type))
        {
            Permission.RequestUserPermission(type);
            MonoPMgr.Instance.StartCoroutine(Check(type, time));
        }
    }

    //延时调用
    static IEnumerator Check(string type, float time)
    {
        yield return new WaitForSeconds(time);
        Get(type, time);
    }
}
//获取设备的读写权限,通过该方法可以尝试获取权限,可将该代码挂载在初始场景,在项目启动阶段向设备发出权限获取请求
        AndroidPermissionMgr.Get(Permission.ExternalStorageWrite, 2);

配置

将下面配置拖进项目中的Plugins/Android文件夹中
链接:https://pan.baidu.com/s/1Y7V5JMnXUHAiWtzB5tah1w
提取码:qing
还有一部非常重要,为了能将截图刷新值相册中,可以将截图存放在设备的Pictures中。
在playing setting->other下将Weirite pemission设置为w外部存储。在这里插入图片描述
截图完整代码,,为了是截图不带UI,可以在生成texture2d时候将UI隐藏,截图结束在将UI显示,当然还有另一种方法截取某个相机下的图片(没研究)。

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
using System.IO;
using System.Security.AccessControl;

/// <summary>
/// 截图保存安卓手机相册
/// </summary>
public class CaptureScreenshotMgr : MonoBehaviour
{
    private string path;
    /// <summary>
    /// 保存按钮点击事件
    /// </summary>
    public void OnScreenShootClick()
    {
        StartCoroutine(ScreenShoot());
    }
    //获取图片的保存路径
    public string ScreenshotPath()
    {
        string filePath = "";
        if (Application.platform == RuntimePlatform.Android)
        {
            filePath = "/storage/emulated/0/Pictures/pictest/";
        }
        if (!Directory.Exists(filePath))
        {
            try
            {
                Directory.CreateDirectory(filePath);
            }
            catch (PathTooLongException)
            {
                Debug.Log("路径或者文件名超过系统定义的最大长度。");
                //txt.text += "路径或者文件名超过系统定义的最大长度。";
            }
            catch (DirectoryNotFoundException)
            {
                //txt.text += "保存目录没有找到。";
                Debug.Log("保存目录没有找到。");
            }
            catch (UnauthorizedAccessException)
            {
                //txt.text += "创建目录失败,因为没有足够的权限。";
                Debug.Log("创建目录失败,因为没有足够的权限。");
            }

        }
            return filePath;
    }
    //截图保存之后刷新相册
    IEnumerator ScreenShoot()
    {
        //保存照片前隐藏保存按钮和返回按钮
        Main05.Instance.SetBtnsShow(false);
        
        //图片大小  
        Texture2D tex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, true);
        yield return new WaitForEndOfFrame();
        tex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, true);
        tex.Apply();
        yield return tex;
        byte[] byt = tex.EncodeToPNG();

        //显示返回按钮
        Main05.Instance.SetBtnsShow(true);
        
        //图片名称,一般以日期命名
        DateTime currentTime = DateTime.Now;
        string fileName = "Custom" + currentTime.Year + currentTime.Month + currentTime.Day + "_" + currentTime.Hour + currentTime.Minute + currentTime.Second + ".png";
        path = ScreenshotPath() + fileName;
        File.WriteAllBytes(path, byt);
        string[] paths = { path };
        //安卓平台才调用安卓的活动刷新相册
        if (Application.platform == RuntimePlatform.Android)
        {
            ScanFile(paths);
        }      
    }
    
    //刷新图片,显示到相册中
    void ScanFile(string[] path)
    {
        using (AndroidJavaClass PlayerActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            AndroidJavaObject playerActivity = PlayerActivity.GetStatic<AndroidJavaObject>("currentActivity");
            using (AndroidJavaObject Conn = new AndroidJavaObject("android.media.MediaScannerConnection", playerActivity, null))
            {
                Conn.CallStatic("scanFile", playerActivity, path, null, null);
            }
        }
    }
}

总结

Unity安卓截图功能,其中截图功能不难实现,无非创建Texture2D,然后转化为二进制数组,对新入门(本人也是)来说难在文件的权限上,尤其Android10以来。
以上是我对Unity安卓截图的总结,第一次做稍微有点混乱,像极了我的组会PPT。如果大家在Unity安卓开发上遇到任何问题,欢迎私信或者在评论区交流沟通。
下周三更新MobSDK的分享功能。

标签:截图,string,安卓,tex,Unity,new,using
来源: https://blog.csdn.net/sunkaik/article/details/121958024

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有