首先微信小游戏获取原生模版广告接口:
const customAd = wx.createCustomAd({
adUnitId: 'adUnit-xxxx',
style: {
left: 10,
top: 76,
width: 375, // 用于设置组件宽度,只有部分模板才支持,如矩阵格子模板
fixed: true // fixed 只适用于小程序环境
}
})
customAd.show()
1.要让广告居中显示主要使用style对象中的left和width来控制
2.获取当前设备窗口大小,这也可以使用微信小游戏提供的接口实现:
wx.getSystemInfo({
success (res) {
console.log(res.model)
console.log(res.pixelRatio)
console.log(res.windowWidth)
console.log(res.windowHeight)
console.log(res.language)
console.log(res.version)
console.log(res.platform)
}
})
3.使用获取到的屏幕宽度减去广告的宽度再除以2就可以得到让广告居中的left数值:
let winSize = wx.getSystemInfoSync();
let bannerWidth = 360;//设置一个广告的宽度
let bannerHeight = 106;//设置一个广告的高度
// 创建原生模板广告实例,提前初始化
let CustomAd = wx.createCustomAd({
adUnitId: '',//填入自己的广告id值
style: {
left: (winSize.windowWidth - bannerWidth) / 2, // 水平居中
top: winSize.windowHeight - bannerHeight - 20, // 底部对齐
width: bannerWidth,
height: bannerHeight,
fixed: true
}
});