微信小游戏原生模版广告居中显示

首先微信小游戏获取原生模版广告接口:

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
        }
    });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值