在我们布局中,经常会采用px作为布局的一个尺寸参考单位,这个单位在浏览器里面已经是布局的标准。
在鸿蒙开发中,提出了一些新的单位用于布局。
物理像素:一般用px来表示
逻辑像素:在布局的时候,底层针对物理像素和屏幕的尺寸关系进行了转化的中间层。
分辨率:代表在屏幕上面到底布局了多少个像素点(发光点)
鸿蒙开发中,要进行布局,我们需要采用官方提供的单位来实现
- px:根据预览器设置的像素,默认1080px,默认参考1080来布局。(不推荐)
- vp:推荐单位,采用当前手机屏幕宽度作为我们的布局参考,不管物理像素到底是多少。可以减少拍屏幕之间的差距。默认不写单位vp
- fp:跟随系统子字体大小设置变化
- lpx:视窗逻辑像素单位,lpx单位为实际屏幕宽度与逻辑宽度(通过designWidth配置)的比值,designWidth默认值为720。当designWidth为720时,在实际宽度为1440物理像素的屏幕上,1lpx为2px大小
像素单位转换
提供其他单位与px单位互相转换的方法。
示例
说明:
直接使用vp2px/px2vp/fp2px/px2fp/lpx2px/px2lpx可能存在UI上下文不明确的问题,建议使用getUIContext获取UIContext实例,再使用UIContext下的vp2px/px2vp/fp2px/px2fp/lpx2px/px2lpx调用绑定实例的接口。
// xxx.ets
@Entry
@Component
struct Example {build() {Column() {Flex({ wrap: FlexWrap.Wrap }) {Column() {Text("width(220)").width(220).height(40).backgroundColor(0xF9CF93).textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12vp')}.margin(5)Column() {Text("width('220px')").width('220px').height(40).backgroundColor(0xF9CF93).textAlign(TextAlign.Center).fontColor(Color.White)}.margin(5)Column() {Text("width('220vp')").width('220vp').height(40).backgroundColor(0xF9CF93).textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12vp')}.margin(5)Column() {Text("width('220lpx') designWidth:720").width('220lpx').height(40).backgroundColor(0xF9CF93).textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12vp')}.margin(5)Column() {Text("width(vp2px(220) + 'px')")// 建议使用this.getUIContext().vp2px().width(vp2px(220) + 'px').height(40).backgroundColor(0xF9CF93).textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12vp')}.margin(5)Column() {Text("fontSize('12fp')").width(220).height(40).backgroundColor(0xF9CF93).textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12fp')}.margin(5)Column() {Text("width(px2vp(220))")// 建议使用this.getUIContext().px2vp().width(px2vp(220)).height(40).backgroundColor(0xF9CF93).textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12fp')}.margin(5)}.width('100%')}}
}