Unity3d截图保存到Android相册的实现
-----------------------------ultrasoon 季风原创---------------------------------------

1.Unity3d场景中先加入屏幕抓图功能:

Application.CaptureScreenshot("Screenshot.png");

这样Screenshot.png就存到了你的app沙盒中,请检查/sdcard/Android/data/com.ultrasoon.MyApp/,这个是我的app沙盒路径.
这个是第一步,之后还要保存到相册中。

2.unity中点击保存到相册按钮
unity部分代码:

 1 public static AndroidJavaClass plugin;
2
3
4 void Awake ()
5 {
6
7 if(Application.platform == RuntimePlatform.Android ) {
8 plugin = new AndroidJavaClass("com.ultrasoon.MyApp.Binding");
9 }
10 }
11 void OnGUI()
12 {
13 if (GUI.Button(new Rect(20, 20, 100, 5), "save"))
14 {
15 //保存到相册,调用自己写的Binding插件
16 plugin.CallStatic("savebuttonClicked");
17
18 }
19 }

3.Binding插件的实现.import对应的package

Binding.cs部分代码:

 1 public static Context context;
2
3 // 保存到相册
4 public static void savebuttonClicked() {
5
6 //取得你XXXXXXXActivity的context.用自己的,不能用this,插件中调用静态的方法
7 context = XXXXXXXActivity.getApplicationContext();
8
9 XXXXXXXActivity.runOnUiThread(new Runnable() {
10 public void run() {
11 // file:///sdcard/Android/data/com.ultrasoon.MyApp/files/Screenshot.png
12 Bitmap bitmap = Binding
13 .getDiskBitmap("/sdcard/Android/data/com.ultrasoon.MyApp/files/Screenshot.png");
14 if (bitmap != null) {
15
16 MediaStore.Images.Media.insertImage(
17 context.getContentResolver(), bitmap, "myPhoto", "");
18 context.sendBroadcast(new Intent(
19 Intent.ACTION_MEDIA_MOUNTED,
20 Uri.parse("file://"
21 + Environment.getExternalStorageDirectory())));
22 Toast.makeText(
23 context,
24 " 恭喜你!照片已保存到你的相册中! ", Toast.LENGTH_SHORT).show();
25 }
26 }
27 });
28
29 }
30
31 // 读图
32 public static Bitmap getDiskBitmap(String url) {
33
34 Bitmap bitmap = null;
35 try {
36 File file = new File(url);
37 if (file.exists()) {
38 bitmap = BitmapFactory.decodeFile(url);
39
40 }
41 } catch (Exception e) {
42
43 }
44 return bitmap;
45 }

4.编译打包插件Binding,打包成jar,复制到unity的Asserts中下面的plugins目录里面。

OK了。
具体细节希望自己摸索!

-----------------------------ultrasoon 季风原创---------------------------------------

04-21 05:49