这两天在做一个分享功能,首先要在shareSDK官网和微博官网上获取app key和app secret之类的信息 这样的方法网上有很多 就不一一赘述了
最终的代码实现 给贴上
using UnityEngine;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
using cn.sharesdk.unity3d;
using UnityEngine.UI;
public class ShareButton : MonoBehaviour
{
private ShareSDK ssdk;
private Camera camera1;
private static ShareButton _instance;
public static ShareButton Instance { get { return _instance; } }
void Start ()
{
_instance = this;
DontDestroyOnLoad(gameObject);
ssdk = GetComponent();
Instance.ssdk.shareHandler = OnShareResultHandler;//注册回调函数
camera1 = GameObject.Find("Main Camera").GetComponent();
}
public void OnShareButtonClick()
{
OnScreenShot();//自定义截屏
ShareContent content = new ShareContent();//分享前,创建对象
content.SetText("恭喜您获得数码兽");//分享文字
content.SetImagePath("/sdcard/DCIM/screensshots/ScreenShot.png");//分享图片
//设置分享来源的站点与站点的url
content.SetSite("鼹鼠游戏");
content.SetSiteUrl("http://www.baidu.com");
content.SetShareType(ContentType.Image);//设定分享内容的主要类型
//PlatformType[] platforms = {PlatformType.SinaWeibo, PlatformType.WeChat};
//设置哪些平台不显示 具体参数 PlatformType 到定义出查看 只对安卓有效 ios的只需上一行的方法就行了
string[] platfsList = {"2", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "23",
"24", "25", "26", "27", "30", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45","46", "48", "50", "51",
"52", "53", "54" };
content.SetHidePlatforms(platfsList);
ssdk.ShowPlatformList(null,content,100,100);
}
void OnScreenShot()
{
RenderTexture rt= new RenderTexture(Screen.width,Screen.height,1);
camera1.targetTexture = rt;
camera1.Render();
RenderTexture.active = rt;
//命名图片
string fileName = "ScreenShot.png";
if (Application.platform == RuntimePlatform.Android)
{
//截屏
Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
texture.Apply();
camera1.targetTexture = null;
RenderTexture.active = null;
Destroy(rt);
//转化为2进制数组
byte[] bytes = texture.EncodeToPNG();
//存储路径
string destination = "/sdcard/DCIM/screensshots";
//若没路径 创建
if (!Directory.Exists((destination)))
{
Directory.CreateDirectory(destination);
}
//保存路径
string pathSave = destination + "/" + fileName;
//写入图片
File.WriteAllBytes(pathSave, bytes);
}
}
void OnShareResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable data)
{
//并非所有平台都会报告正确的状态
if (state == ResponseState.Success)
{
Utility.MakeToast("分享成功");
}
else if (state == ResponseState.Fail)
{
Utility.MakeToast("分享失败");
}
else if (state == ResponseState.Cancel)
{
Utility.MakeToast("分享操作被取消");
}
}
}