【Laya】微信分享功能

时间:2024-03-21 19:42:51

使用方法

1. 被动转发

  在gamemain,这个游戏开始的脚本,读取完数据后,就添加这行脚本。

【Laya】微信分享功能

 2. 主动转发

【Laya】微信分享功能

3. 这里有个图片,得找美术要一张。 位置是 

【Laya】微信分享功能

4. 具体脚本如下图。 直接复制粘贴就好,即可使用。

/*
* 平台管理器;
*/
class PlatformManager extends Singleton {
    //---------------instance begin----------------------------------------------------
    public static get Instance(): PlatformManager {
        if (!this._instance) {
            this._instance = new PlatformManager();
        }
        return this._instance as PlatformManager;
    }
    private static _instance: PlatformManager;
    //---------------instance end----------------------------------------------------

    private _curPlatform: PlatformBase = null;

    public InitPlatform() {
        //需要根据配置加载对应的平台
        let initData: PingTaiData =  new PingTaiData(ConstDataManager.Instance.GetValueEx("pingtai","wechat"));
        let str: string = "";
        if (initData != null)  {
            str = initData.name;
        }

        switch (str)  {
            case "wechat":
                {
                    this._curPlatform = new WechatPlatform();
                }
                break;
            case "web":
            default:
                {
                    this._curPlatform = new WebPlatform();
                }
                break;

        }

    }

    //---------------相册 begin----------------------------------------------------
    public ChooseImg(func: Function) {
        if (this._curPlatform != null) {
            this._curPlatform.ChooseImg(func);
        }
    }

    public ReadImg(path: string, func: Function) {
        if (this._curPlatform != null) {
            this._curPlatform.ReadImg(path, func);
        }
    }
    //---------------相册 end----------------------------------------------------

    //截屏
    public SaveScreenToPhoto(func : Function)
    {
        if (this._curPlatform != null) {
            this._curPlatform.SaveScreenToPhoto(func);
        }
    }

    public OnSaveScreenToPhoto(witdh: number, height: number, offsetX: number, offsetY: number, func: Function) 
    {
        if (this._curPlatform != null) {
            this._curPlatform.OnSaveScreenToPhoto(witdh,height,offsetX,offsetY,func);
        }
    }

    //分享
    public UIShare(shareType : number,succfunc:Function = null,losefunc:Function = null){
        if (this._curPlatform != null) {
            this._curPlatform.UIShare(shareType,succfunc,losefunc);
        }
     }
}

class PingTaiData
{
    public name : string;
    constructor(str:string)
    {
        this.name =str;
    }
}

 

/*
* 微信平台;
*/

class WechatPlatform implements PlatformBase {
    //微信图片临时路径
    private picSavePath: string;
    //微信的接口
    private wx: any = Laya.Browser.window.wx;
    public ChooseImg(func: Function) {
        if (Laya.Browser.onMiniGame) {
            //回调
            let data: string;
            this.wx.chooseImage({
                count: 1,
                success: (res) => {
                    // 无论用户是从相册选择还是直接用相机拍摄,路径都是在这里面
                    let filePath = res.tempFilePaths[0];
                    const fs = this.wx.getFileSystemManager();
                    fs.saveFile({
                        tempFilePath: filePath, // 传入一个本地临时文件路径
                        success: (res) => {
                            this.picSavePath = res.savedFilePath;
                            if (func != null) {
                                func(res.savedFilePath);
                            }
                        }
                    });
                }
            });
        }
    }

    public ReadImg(path: string, func: Function) {
        if (Laya.Browser.onMiniGame) {
            //回调
            let data: string;
            const fs = this.wx.getFileSystemManager();
            fs.readFile({
                filePath: path,
                encoding: 'base64',
                success: (res) => {
                    if (func != null) {
                        func("data:image/jpeg;base64," + res.data);
                    }
                }
            });
        }
    }


    //获得图片
    public getImageInfo(basePath: string, func: Function) {
        if (Laya.Browser.onMiniGame) {
            this.wx.getImageInfo({
                src: basePath,
                success: (res) => {
                    this.SaveImg(res.path, func);
                }
            });
        }
    };

    //base64读入缓存并保存到相册
    public OnSaveScreenToPhoto(witdh: number, height: number, offsetX: number, offsetY: number, func: Function) {
        if (!Laya.Browser.onMiniGame) {
            if (func != null) {
                func();
            }
            return;
        }
        let fileManager = this.wx.getFileSystemManager();
        let timestamp = new Date().getTime();
        //HTMLCanvas 是 Html Canvas 的代理类,封装了 Canvas 的属性和方法。。请不要直接使用 new HTMLCanvas!
        //此处将canvas指定区域进行截屏
        let htmlC = Laya.stage.drawToCanvas(witdh, height, -offsetX, -offsetY);
        let canvas = htmlC.getCanvas();
        let data = canvas.toDataURL("image/png");//.replace("image/png", "image/octet-stream"); // 获取生成的图片的url  

        let filePath = `${this.wx.env.USER_DATA_PATH}/qrcode_${timestamp}.png`;
        fileManager.writeFile({
            filePath: filePath,
            data: data.substring(data.indexOf(',') + 1),
            encoding: 'base64',
            success: res => {
                this.SaveImg(filePath, func);
            },
            fail: res => {
                this.wx.showToast({
                    title: '保存图片失败!',
                })
            }
        })
    }

    //base64读入缓存并保存到相册
    public SaveScreenToPhoto(func: Function) {
        this.OnSaveScreenToPhoto(Laya.stage.width, Laya.stage.height, 0, 0, func);
    }

    //保存到相册
    public SaveImg(path: string, func: Function) {
        if (!Laya.Browser.onMiniGame) {
            if (func != null) {
                func();
            }
            return;
        }
        this.wx.saveImageToPhotosAlbum({
            filePath: path,
            success: res => {
                if (func != null) {
                    func();
                }
                this.wx.showToast({
                    title: '保存图片成功!',
                })
            },
            fail: res => {
                if (func != null) {
                    func();
                }
                this.wx.showToast({
                    title: '保存图片失败!',
                })
            }
        })
    }

    GetShareStr():string
    {
        let str:string = "我已长命百岁,你能坚持多久";
         var list: string[] = ClientTools.GetStringList( ConstDataManager.Instance.GetValueEx("fenxiangstr","我已长命百岁,你能坚持多久"),";");
         if (list != null)
         {
             if (list.length == 1)
                str = list[0];
             else
             {
                 let randomNum: number = Math.floor(Math.random() * list.length);
                 str =  list[randomNum];
             }
         }
         return str;
    }
    //2是被动转发,1是主动转发
    public UIShare(shareType: number,succfunc:Function,losefunc:Function) {
        if (succfunc != null)
            succfunc();
        if (Laya.Browser.onMiniGame) {
            let str:string = this.GetShareStr();
            if (shareType == 1) {
                this.wx.shareAppMessage({
                    title:str,
                    imageUrl: 'res/img/share.jpg',
                    success: () => {
                        if (succfunc != null)
                            succfunc();
                        this.wx.showToast({
                            title: '分享成功',
                        })
                    },
                    fail: () => {
                        if (losefunc != null)
                            losefunc();
                        this.wx.showToast({
                            title: '分享失败',
                        })
                    }
                })
            }

            if (shareType == 2) {
                this.wx.showShareMenu({
                    withShareTicket: true
                })
                this.wx.onShareAppMessage(function () {
                    return {
                        title: str,
                        imageUrl: 'res/img/share.jpg',
                    }
                })
            }
        }
    }


}
/*
* 网页平台;
*/

class WebPlatform implements PlatformBase {
    private _curstomImg: string = "";

    public ChooseImg(func: Function) {
        //回调
        if (func != null) {
            func("trail_a.png");
        }
    }

    public ReadImg(path: string, func: Function) {
        Laya.loader.load(path, Laya.Handler.create(this, () => {
            //回调
            if (func != null) {
                func(path);
            }
        }));
    }

    public SaveScreenToPhoto(func: Function)  {
        if(func != null)
        {
            func();
        }
    }

    public UIShare(shareType : number,succfunc:Function,losefunc:Function){
          
     }

     public OnSaveScreenToPhoto(witdh : number , height : number , offsetX : number , offsetY : number ,func: Function)
     {
         if(func != null)
         {
             func();
         }
     }
}

 

/*
* 平台接口base;
*/
interface IPlatformBase {
    ChooseImg(func: Function);
    ReadImg(path: string, func: Function);
    SaveScreenToPhoto(func: Function);
    OnSaveScreenToPhoto(witdh: number, height: number, offsetX: number, offsetY: number, func: Function);
}

class PlatformBase implements IPlatformBase {
    public ChooseImg(func: Function)  {

    }

    public ReadImg(path: string, func: Function)  {

    }

    public SaveScreenToPhoto(func: Function)  {

    }

    public UIShare(shareType: number,succfunc:Function,losefunc:Function) {

    }

    public OnSaveScreenToPhoto(witdh: number, height: number, offsetX: number, offsetY: number, func: Function)  {

    }
}