Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Unity 應用中分享圖片與文字到好友的實現

編輯:關於 Android 程式設計

首先在配置文件中加入讀寫 SD 卡的權限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

以下透過 Unity 的 C# 腳本,調用 Android 原生插件來實現截屏與分享功能:

using UnityEngine;
using System.Collections;
using System.IO;

public class Share : MonoBehaviour {
    public static string imagePath;
    static AndroidJavaClass sharePluginClass;
    static AndroidJavaClass unityPlayer;
    static AndroidJavaObject currActivity;
    private static Share mInstance;

    public static Share instance {
        get { return mInstance; }
    }

    void Awake() {
        mInstance = this;
    }

    void Start() {
        imagePath = Application.persistentDataPath + "/HKeyGame.png";
        sharePluginClass = new AndroidJavaClass("com.ari.tool.UnityAndroidTool");
        if (sharePluginClass == null) {
            Debug.Log("sharePluginClass is null");
        } else {
            Debug.Log("sharePluginClass is not null");
        }
        unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        currActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
    }

    public void CallShare(string handline, string subject, string text, bool image) {
        Debug.Log("share call start : " + imagePath);
        if (image) {
            sharePluginClass.CallStatic("share",
                    new object[] { handline, subject, text, imagePath });
        } else {
            sharePluginClass.CallStatic("share",
                    new object[] { handline, subject, text });
        }
        Debug.Log("share call end");
    }

    public void ScreenShot() {
        StartCoroutine(GetCapture());
    }

    IEnumerator GetCapture() {
        yield return new WaitForEndOfFrame();
        int width = Screen.width;
        int height = Screen.height;
        Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
        tex.ReadPixels(new Rect(0, 0, width, height), 0, 0, true);
        byte[] imagebytes = tex.EncodeToPNG();  // 轉化為 png 圖
        tex.Compress(false);                    // 對屏幕緩存進行壓縮
        // image.mainTexture = tex;             // 顯示縮略圖
        File.WriteAllBytes(Application.persistentDataPath + "/HKeyGame.png",
                imagebytes);                    // 存儲 png 圖
        Debug.Log(Application.persistentDataPath);
    }
}

這段代碼的關鍵在於:先透過 ScreenShot() 觸發協程截取當前畫面並保存為 PNG,再透過 CallShare() 調用 Android 原生分享插件,把文字與圖片路徑傳遞過去,由系統分享面板完成社交分享。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved