一、原则:

  1. 组件大小能使用百分比尽量使用百分比

  2. 需要适配多分辨率的px值在hml文件中设置

二、原理:

​ 使用表宽作为适配的基准值,比如在表宽为466的表上组件的大小值为a,那么在宽度为360的表上组件的大小值为a * 360 / 466,我们将缩放比例360 / 466叫做benchmark,当我们在466的表上适配完成后,将所有的组件和字体大小值乘以benchmark即可完成多分辨率适配。

三、实例:

  1. 首先找一个基准表型进行界面设计,这里使用的是466*466的圆形表作为基准表。然后在app.js中计算应用内需要用到的大小。
//app.js
import device from '@system.device'

export default {
    data: {
        style: {    // 将所有需要的大小值添加至这里
            size_20: 20,
            size_25: 25,
            size_30: 30,
            size_35: 35,
            size_40: 40,
            size_48: 48,
            size_50: 50,
            size_60: 60,
            size_70: 70,
            size_80: 80,
            size_90: 90,
            size_100: 100,
            size_110: 110
        }
    },

    onCreate() {
        console.info('Application onCreate');
        device.getInfo({
            success: function (data) {
                console.info("get Device Info success. screenSize:" + data.windowWidth+"*"+data.windowHeight)
                let benchmark = data.windowWidth / 466    // 获取表宽计算需要缩放的比例
                const keys = Object.keys(getApp().data.style)    // 只能通过getApp().data.style访问,不能使用this.style
                keys.forEach((key) => {
                    getApp().data.style[key] = Math.round(getApp().data.style[key] * benchmark)    // 将所有size值适配当前表
                })
            },
            fail: function (data, code) {
                console.info("get Device Info fail. code:" + code + ",msg:" + data)
            }
        })
    },

    onDestroy() {
        console.info('Application onDestroy')
    }
};
  1. 在页面中使用适配后的样式大小
// page.js
export default {
    data: {
        style: getApp().data.style    // 使用适配后的样式
    },
    
    onInit() {},
}

//page.hml
<stack class="container">
    <div class="main">
        <image style="width: {{style.size_80}}px; height: {{style.size_80}}px;" src="/common/image/avatar.png"></image>
    </div>
    <div class="logOut" if="{{showLogOut}}" onswipe="none">
        <text class="txt-message" style="font-size: {{style.size_35}}px;">{{$t('strings.logOutTips')}}</text>
        <div class="button-div" style="height: {{style.size_100}}px;">
            <image class="cancel" style="width: {{style.size_100}}px; height: {{style.size_100}}px;"
                src="/common/image/cancel.png" onclick="btnCancel"/>
            <image class="confirm" style="width: {{style.size_100}}px; height: {{style.size_100}}px;"                                             src="/common/image/confirm.png" onclick="btnOk"/>
        </div>
    </div>
</stack>

四、注意

​ style的大小计算是在app启动时执行的,由于获取设备大小,style遍历计算需要耗费一定的时间,所以进入index页面时可能大小计算还未完成,导致显示的仍是原始大小。因此推荐将index页设置为启动页(页面样式使用百分比),停留一段时间(>= 1s)后再进入应用的使用界面。

Logo

社区规范:仅讨论OpenHarmony相关问题。

更多推荐