鸿蒙界面开发2
设计资源-svg 图标
需求:界面中展示图标 → 可以使用 svg 图标(任意放大缩小不失真、可以改颜色)
Image($r('app.media.ic_dianpu'))
.width(40)
.fillColor('#b0473d')
使用方式:
-
设计师提供:基于项目设计的图标,拷贝到项目目录使用
-
图标库中选取:找合适的图标资源 → 下载(svg) → 拷贝使用
布局元素的组成
内边距 padding
作用:在 组件内 添加 间距,拉开内容与组件边缘之间的距离
Text('内边距padding')
.padding(20) // 四个方向内边距均为20
Text('内边距padding')
.padding({
top: 10,
right: 20,
bottom: 40,
left: 80
}) // 四个方向内边距分别设置
外边距 margin
作用:在 组件外 添加 间距,拉开两个组件之间的距离
Text('外边距margin')
.margin(20) // 四个方向外边距均为20
Text('外边距margin')
.margin({
top: 10,
right: 20,
bottom: 40,
left: 80
}) // 四个方向外边距分别设置
边框 border
作用:给组件添加边界,进行装饰美化。
Text('边框语法')
.border({
width: 1, // 宽度(必须设置)
color: '#3274f6', // 颜色
style: BorderStyle.Solid // 样式
}) // 四个方向相同
Text('边框语法').border({
width: {
left: 1, right: 2
},
color: {
left: Color.Red, right: Color.Blue
},
style: {
left: BorderStyle.Dashed,
right: BorderStyle.Dotted
}
}) // top、right、bottom、left
设置组件圆角
属性:.borderRadius(参数)
参数:数值 或 对象 (四个角单独设置)
Ø topLeft:左上角
Ø topRight:右上角
Ø bottomLeft:左下角
Ø bottomRight:右下角
-
设置组件圆角?
borderRadius(数值 或 对象)
-
设置圆角语法?
Text('圆角语法')
.borderRadius(5) // 四个圆角相同
.borderRadius({
topLeft: 5,
topRight: 10,
bottomRight: 15,
bottomLeft: 20
}) // 四个方向圆角,单独设置
特殊形状的圆角设置
-
正圆
Text('正圆') .width(100) // 宽度高度一样 .height(100) .borderRadius(50) // 圆角是宽或高的一半
-
胶囊按钮(左右半圆)
Text('胶囊按钮') .width(150) // 宽度大,高度小 .height(50) .borderRadius(25) // 圆角是高的一半
背景属性
属性方法 | 属性 |
---|---|
背景色 | backgroundColor |
背景图 | backgroundImage |
背景图位置 | backgroundImagePosition |
背景图尺寸 | backgroundImageSize |
网页中,使用 背景图 实现 装饰 效果。
背景图 - backgroundImage
属性:.backgroundImage (背景图地址, 背景图平铺方式 - 枚举 ImageRepeat)
背景图平铺方式 ImageRepeat:(可省略)
Ø NoRepeat:不平铺,默认值
Ø X:水平平铺
Ø Y:垂直平铺
Ø XY:水平垂直均平
Text('我是文本')
.backgroundImage($r('app.media.flower'), ImageRepeat.XY)
背景图位置 - backgroundImagePosition
作用:调整背景图在组件内的显示位置,默认显示位置为组件左上角
属性:.backgroundImagePosition (坐标对象 或 枚举)
参数:
Ø 位置坐标: { x: 位置坐标, y: 位置坐标 }
背景定位默认单位 → px:实际的物理像素点,设备出厂,就定好了【分辨率单位】
宽高默认单位 → vp:虚拟像素,相对于不同的设备会自动转换,保证不同设备视觉一致 (推荐)
函数:vp2px(数值) 将 vp 进行转换,得到 px 的数值
Ø 枚举 Alignment
-
单位 vp 和 px 更推荐使用哪个 ?
vp 基于设备自动转换,保证不同设备视觉一致
-
如何将 vp 转 px ?
vp2px(数值)
背景图尺寸 - backgroundImageSize
作用:背景图缩放
属性:.backgroundImageSize ( 宽高对象 或 枚举 )
参数:
Ø 背景图宽高:{ width: 尺寸, height: 尺寸 }
Ø 枚举 ImageSize:
Contain:等比例缩放背景图,当宽或高与组件尺寸相同停止缩放
Cover:等比例缩放背景图至图片完全覆盖组件范围
Auto:默认,原图尺寸
Text()
.backgroundImage($r('app.media.flower'))
.backgroundImageSize({ width: 250, height: 100 })
.backgroundImageSize(ImageSize.Cover)
线性布局
线性布局 ( LinearLayout ) 通过线性容器 Column 和 Row 创建。
- Column 容器:子元素 垂直方向 排列
- Row 容器: 子元素 水平方向 排列
排布主方向上的对齐方式 (主轴)
属性:.justifyContent(枚举 FlexAlign)
(Row 组件的 justifyContent 属性效果相似)
交叉轴对齐方式
属性:alignItems()
参数:枚举类型
Ø 交叉轴在水平方向:HorizontalAlign
Ø 交叉轴在垂直方向:VerticalAlign
自适应伸缩
设置 layoutWeight 属性的 子元素 与 兄弟元素,会 按照权重 进行分配 主轴 的 空间 (剩余空间)
语法:.layoutWeight(数字)
Row() {
Text('左侧')
.layoutWeight(1)
.height(50)
.backgroundColor(Color.Pink)
Text('右侧')
.width(70)
.height(50)
.backgroundColor(Color.Orange)
}