上一篇我们已经介绍了android上面相关代码的书写,这部分主要是介绍如何在unity里面调用andorid里面自己生成的jar包和相关资源,内容如下:
1.在U3d当中新建一个工程再将相关的文件拷入如下图:(程序相关的配置文件等)
2.在bin文件里面放入刚才我们从android工程里面导出的相关jar包
3.编写脚本添加图片和截屏的脚本并将其绑定在MainCammer里面
using UnityEngine;
using System.Collections;
public class AddPicture : MonoBehaviour
{
private Texture2D tex ;
void OnGUI()
{
if (GUI.Button(new Rect(200, 20, 100, 100), "添加图片"))
{
//调用我们制作的Android插件打开手机相册
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("Main", "takeSave");
}
if (tex)
{
GUI.DrawTexture(new Rect(100,100,300,300) , tex) ;
}
}
void message(string str)
{
StartCoroutine (LoadTexture (str));
}
IEnumerator LoadTexture(string fileName)
{
string path = "file://" + Application.persistentDataPath + "/sourcefiles/" + fileName;
WWW www = new WWW (path);
while(!www.isDone)
{
}
yield return www;
tex = www.texture;
}
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
public class Screenshot : MonoBehaviour
{
private bool isStart = false;
void OnGUI()
{
if(GUI.Button(new Rect(100, 20, 100, 100), "截图"))
{
isStart = true;
}
}
void OnPostRender()
{
if (isStart)
{
Rect rect = new Rect(0, 0, Screen.width, Screen.height);
// 先创建一个的空纹理,大小可根据实现需要来设置
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.ARGB32, false);
// 读取屏幕像素信息并存储为纹理数据,
screenShot.ReadPixels(rect, 0, 0);
screenShot.Apply();
// 然后将这些纹理数据,成一个png图片文件
byte[] bytes = screenShot.EncodeToPNG();
string path = Application.persistentDataPath + "/Screenshot";
if (!Directory.Exists(path))
{
//创建文件夹
Directory.CreateDirectory(path);
}
string filename = path + "/Screenshot" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
System.IO.File.WriteAllBytes(filename, bytes);
print(string.Format(filename));
#if(UNITY_ANDROID)
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("RefreshPic", filename);
#endif
#if(UNITY_IPHONE)
<span style="white-space:pre"> </span>SDK.SavePhoto(filename);
#endif
isStart = false;
}
}
}
4.在unity里面运行项目,需要注意的是(playerSettings.bundleIdentifier:要与android的包名一致)
5.build&run