Unity-Sdk—ShareSDK分享图片到微信

一、准备步骤:

       1、登录ShareSDK官网,添加一个应用

       2、登录微信公众平台,创建一个移动应用

       3、新建一个Unity工程,按照Unity快速集成文档创建工程

二、编写简单测试代码并挂在MainCamera上:

using UnityEngine;
using System.Collections;
using cn.sharesdk.unity3d;
using System;

public class ShareSDKTest : MonoBehaviour {
    public ShareSDK ssdk;
    // Use this for initialization
    private void Start () {
        ssdk = gameObject.GetComponent();
        ssdk.shareHandler = OnShareResultHandler;

    }

    private void OnGUI()
    {
        if(GUI.Button(new Rect(100, 100, 100, 50), "Share"))
        {
            ShareContent content = new ShareContent();
            content.SetText("this is a test string.");
            content.SetImagePath(Application.persistentDataPath + "/Screenshot.png");
            content.SetTitle("test title");
            content.SetShareType(ContentType.Image);
            ssdk.ShareContent(PlatformType.WeChat, content);
        }
        if(GUI.Button(new Rect(300, 100, 100, 50), "Capture"))
        {
            StartCoroutine(CaptureCoroutine());

        }
    }

    private static IEnumerator CaptureCoroutine()
    {
        yield return new WaitForEndOfFrame();
        Rect rect = new Rect(0, 0, Screen.width, Screen.height);
            // 先创建一个的空纹理,大小可根据实现需要来设置
            Texture2D texture = null;
            if (texture == null)
            {
                texture = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);

            }
            // 读取屏幕像素信息并存储为纹理数据,  
            texture.ReadPixels(rect, 0, 0);
            texture.Apply();
            byte[] bytes = texture.EncodeToPNG();
            System.IO.File.WriteAllBytes(Application.persistentDataPath + "/Screenshot.png", bytes);
    }

    private void OnShareResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable data)
    {
        if(state == ResponseState.Success)
        {

        }
        else
        {
            Debug.Log("Failure");
        }
    }  
}

三、导出apk包安装测试,如果:

Unity-Sdk—ShareSDK分享图片到微信_第1张图片

      点击Capture截屏并保存在Application.persistentDataPath下,点击Share打开微信并选择一个好友进行发送

四、测试过程中的坑点:

      1、不能再Mono上直接定义存储路径string path = Application.persistentDataPath + "/Screenshot.png";

      2、存储路径必须是可以读写的路径,不能为工程中的路径,比如Application.dataPath如果分享的时候找不到图片路径,那么分享的图片为空,只有分享的字符串

你可能感兴趣的:(GameWorld,Unity-SDK,unity-sdk)