一、ArkUI 基础概念
ArkUI(方舟开发框架)是构建 HarmonyOS 应用界面的框架,其最小构建单位是"组件"。
常用系统组件
组件 |
描述 |
---|---|
Text |
显示文本 |
Image |
显示图片 |
Column |
列,内容垂直排列 |
Row |
行,内容水平排列 |
Button |
按钮 |
二、通用属性
基本属性
属性 |
描述 |
---|---|
width |
宽度 |
height |
高度 |
backgroundColor |
背景色 |
尺寸单位
- •
px:物理像素,设备实际拥有的像素点
- •
vp:虚拟像素(推荐使用),自动根据设备显示能力转换
Text('Hello') .width(100) // 默认单位vp .height(50)
三、文本属性
字体样式
Text('示例文本') .fontSize(16) // 字体大小
.fontColor('#333') // 字体颜色
.fontStyle(FontStyle.Italic) // 斜体
.fontWeight(FontWeight.Bold) // 加粗
文本布局
Text('多行文本示例\n第二行') .lineHeight(24) // 行高
.textAlign(TextAlign.Center) // 水平居中
.align(Alignment.Top) // 垂直顶部对齐
.textIndent(20) // 首行缩进
文本溢出处理
Text('这是一段很长的文本内容...')
.maxLines(1)
.textOverflow({overflow: TextOverflow.Ellipsis})
四、图片组件
基本用法
Image($r('app.media.example')) // 本地资源
.width(200)
.height(150)
.backgroundColor(Color.Gray) // 背景色
图片填充模式
// 等比缩放,可能留白 Image($r('app.media.cat')) .objectFit(ImageFit.Contain)
// 等比填充,可能裁剪 Image($r('app.media.cat')) .objectFit(ImageFit.Cover) // 默认
// 非等比填充 Image($r('app.media.cat')) .objectFit(ImageFit.Fill)
五、综合案例
QQ音乐卡片案例
@Entry
@Component
struct MusicCard {
build() {
Column() {
Column() {
Text('我的年度歌手榜')
.fontSize(14)
.fontColor('#bdbdbd')
.lineHeight(40)
Text('周杰伦')
.fontSize(24)
.fontWeight(700)
.lineHeight(50)
Image($r('app.media.zhoujielun'))
.width(60)
.height(60)
.borderRadius(30)
Text('真爱就是循环一千遍')
.fontSize(14)
.fontColor('#999')
.lineHeight(40)
}
.width(200)
.height(200)
.backgroundColor('#fff')
.borderRadius(10)
.padding(10)
}
.width('100%')
.height('100%')
.backgroundColor('#f5f7f8')
.justifyContent(FlexAlign.Center)
}
}
百度小说简介案例
@Entry
@Component
struct NovelIntro {
build() {
Row() {
Image($r('app.media.novel_cover'))
.width(120)
.height(160)
.margin({right: 15})
Column() {
Text('三体')
.fontSize(18)
.fontWeight(FontWeight.Bold)
.margin({bottom: 5})
Text('作者:刘慈欣')
.fontSize(14)
.fontColor('#666')
.margin({bottom: 10})
Text('《三体》是刘慈欣创作的系列长篇科幻小说...')
.fontSize(14)
.maxLines(3)
.textOverflow({overflow: TextOverflow.Ellipsis})
}
.layoutWeight(1)
}
.padding(15)
.width('100%')
}
}
六、最佳实践
- 1.
优先使用vp单位:确保不同设备显示一致
- 2.
合理使用文本溢出处理:保证UI整洁
- 3.
图片优化:选择合适的objectFit模式
- 4.
组件组合:灵活使用Column和Row构建复杂布局
通过掌握这些基础组件和样式属性,您已经能够构建出美观且功能完善的HarmonyOS应用界面。