首先是官方的例子
可以看到官方给出的例子如下:
const button = wx.createUserInfoButton({
type: 'text',
text: '获取用户信息',
style: {
left: 10,
top: 76,
width: 200,
height: 40,
lineHeight: 40,
backgroundColor: '#ff0000',
color: '#ffffff',
textAlign: 'center',
fontSize: 16,
borderRadius: 4
}
})
button.onTap((res) => {
console.log(res)
})
实际上,虽然给出了这个按钮的属性,但是对于一些小白来说还是不懂得如何使用,比如说这个按钮的位置的放置,所以我将上述代码进行了一些调整
createLoginButton() {
if (typeof (wx) != 'undefined') {
//获取系统信息的宽度
let sysInfo = wx.getSystemInfoSync();
let screenW = sysInfo.screenWidth;
let screenH = sysInfo.screenHeight;
let rate = screenW / 750;//设计分辨率为750*1334
let self = this;
//根据你图片的大小调整对应的长宽高,并且在不同的分辨率下大小也会对应变化,我的图片是418*160
let width = 418 * rate;
let height = 160 * rate;
const button = wx.createUserInfoButton({
type: 'image',
image: "images/ksyx.png",//图片的位置是在打包构建后的bulid里的根目录开始而不是项目目录
style: {
//设置位置
left: screenW / 2 - width / 2,
top: screenH/2 + 100,
width: width,
height: height
}
})
button.onTap((res) => {
console.log('点击授权按钮', res)
if (res && res.userInfo) {
button.destroy();
self.Loadmenu();//载入下一个场景
}
})
}
}
在上述代码中,它的意义在于创建一个按钮,如果授权成功就会加载到下一个页面并且下一次便不会触发,不授权的话便会在当前页面停留直到用户同意授权,这样你就可以从res中获得用户的头像id等信息并且在你需要的地方显示出来
如果需要一个覆盖全屏的透明按钮的话,可以参考一下群友提供的代码
//创建一个透明按钮在cc.Button的node节点上
createAuthorizeBtn(btnNode:cc.Node) {
let btnSize = cc.size(btnNode.width+10,btnNode.height+10);
let frameSize = cc.view.getFrameSize();
let winSize = cc.director.getWinSize();
// console.log("winSize: ",winSize);
// console.log("frameSize: ",frameSize);
//适配不同机型来创建微信授权按钮
let left = (winSize.width*0.5+btnNode.x-btnSize.width*0.5)/winSize.width*frameSize.width;
let top = (winSize.height*0.5-btnNode.y-btnSize.height*0.5)/winSize.height*frameSize.height;
let width = btnSize.width/winSize.width*frameSize.width;
let height = btnSize.height/winSize.height*frameSize.height;
// console.log("button pos: ",cc.v2(left,top));
// console.log("button size: ",cc.size(width,height));
let self = this;
self.btnAuthorize = wx.createUserInfoButton({
type: 'text',
text: '',
style: {
left: left,
top: top,
width: width,
height: height,
lineHeight: 0,
backgroundColor: '',
color: '#ffffff',
textAlign: 'center',
fontSize: 16,
borderRadius: 4
}
})
self.btnAuthorize.onTap((uinfo) => {
console.log("onTap uinfo: ",uinfo);
if (uinfo.userInfo) {
console.log("wxLogin auth success");
wx.showToast({title:"授权成功"});
}else {
console.log("wxLogin auth fail");
wx.showToast({title:"授权失败"});
}
});
}