ArkUI 5.0 核心特性与实战案例
一、核心特性
1. 声明式UI范式升级
核心优势:通过链式语法描述UI状态与逻辑关系,代码可读性提升300%(华为实验室数据)。
代码示例:
less
@Entry
@Component
struct WeatherCard {
@State temperature: number = 26;
build() {
Column() {
Text(`当前温度:${this.temperature}℃`)
.fontColor(this.temperature > 30 ? Color.Red : Color.Blue) // 动态样式
.onClick(() => {
this.temperature += 1; // 点击更新状态
})
}
}
}
技术亮点:
- 自动脏检查:仅刷新变化部分,渲染性能提升40%
- 类型安全:ArkTS静态类型检查避免85%的UI渲染错误
2. 跨设备自适应布局
三大适配能力:
- 断点系统:根据屏幕尺寸自动切换布局(手机/平板/车机)
- 原子化栅格:12列栅格系统支持百分比精准适配
- 动态资源:自动选择适配当前设备的图片/字体
代码示例:
scss
Row() {
Image($r("app.media.logo"))
.objectFit(ImageFit.Contain)
.gridSpan(6) // 在手机占6列(50%宽度)
.breakpoint({
'width > 600px': { gridSpan: 4 }, // 平板布局
'width > 1024px': { gridSpan: 3 } // 桌面布局
})
}
.gridTemplateColumns('1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr')
二、基础组件深度解析
1. Text组件:智能文本渲染
关键属性:
scss
Text('HarmonyOS Next')
.fontSize(20)
.fontWeight(FontWeight.Bold)
.textOverflow({ overflow: TextOverflow.Ellipsis }) // 超出省略
.maxLines(1)
.copyOption(CopyOptions.Enabled) // 允许用户长按复制
2. Button组件:交互增强设计
样式定制案例:
less
Button('立即购买')
.size({ width: '80%', height: 50 })
.backgroundColor('#FF007A')
.stateEffect(true) // 启用按压态效果
.hoverEffect(HoverEffect.Scale) // 桌面端悬浮缩放
.onClick(() => {
// 处理点击事件
})
交互扩展:
- 手势支持:长按/滑动/组合手势绑定
- 动效库:内置30+种Material/Fluent风格动画
3. Image组件:高性能媒体处理
进阶用法:
less
Image($r('app.media.product'))
.interpolation(ImageInterpolation.High) // 高质量缩放
.sourceSize({ width: 300, height: 300 }) // 按需加载
.transition(ImageTransition.fade(1000)) // 渐显动画
.onComplete(() => {
.log('图片加载完成');
})
2025优化:
- WebP 2.0支持:体积减少50%
- AI超分:低分辨率图智能修复
三、ArkUI 5.0实战:构建商品详情页
1. 组件组合技巧
scss
Scroll() {
Column() {
// 1. 商品图片轮播
Swiper() {
ForEach(this.productImages, (img) => {
Image(img).aspectRatio(1)
})
.indicator(true)
// 2. 商品信息
.fontSize(24)
.fontColor('#FF5000')
// 3. 规格选择
Flex({ wrap: FlexWrap.Wrap }) {
ForEach(this.specs, (spec) => {
.padding(10).borderRadius(15)
})
}
// 4. 操作按钮
Button('加入购物车').width('90%')
}
}
2. 响应式布局技巧
scss
@media (orientation: landscape) {
.product-detail
flex-direction: row; // 横屏切换为行布局
}
}
四、开发者效率工具链
1. 实时预览增强
多设备同屏调试:同时查看手机/手表/车机效果
状态注入:直接在预览界面修改@State变量
2. UI检查器
操作路径:Tools → ArkUI Inspector
功能:
- 查看组件层级树
- 实时编辑属性值
- 性能瀑布流分析
五、状态管理
1. 状态装饰器
装饰器 | 作用域 | 典型场景 |
---|---|---|
@Observed | 全局/共享状态 | 跨组件状态同步(如用户登录信息) |
@State | 组件内部状态 | 组件生命周期内的本地状态(如弹窗开关) |
@Provide | 父组件状态提供 | 向下传递可订阅的状态 |
@Consume | 子组件状态订阅 | 接收父组件提供的状态 |
@Trace | 调试辅助 | 追踪状态变更路径,优化性能 |
2. 状态传递模式对比
按值传递 vs 按引用传递
- 按值传递:静态数据,无响应式,适合配置项。
- 按引用传递:动态绑定,响应式,适合共享状态。
代码示例:状态传递对比
less
// 按值传递(静态数据)
@Component
struct StaticLabel {
@Param label: string; // 父组件传递的值不可变
build() { Text(this.label).fontSize(20) }
}
// 按引用传递(动态绑定)
class UserState { @Observed name: string = 'Guest'; }
@Component
struct Greeting {
@Provide userState: UserState = new UserState(); // 全局状态
build() {
Button('Login').onClick(() => { this.userState.name = 'John'; })
Text(`Hello, ${this.userState.name}`); // 状态变更自动刷新
}
}
六、布局系统
1. Flex布局
scss
Row({ justifyContent: FlexAlign.SpaceBetween }) {
Text('左').width('33%')
Text('中').width('33%')
Text('右').width('33%')
}
2. Grid布局
scss
Grid({ columns: 3, rows: 2 }) {
ForEach(data, (item) => Text(item).width('100%'))
}
七、动画与转场
1. 属性动画
scss
Column() {
LoadingProgress()
.width(60)
.height(60)
}
.width(80)
.height(80)
.borderRadius(40)
.backgroundColor(Color.White)
.justifyContent(FlexAlign.Center)
.position({ x: 90, y: 0 })
.opacity(this.loadingOpacity)
.animation({
duration: 300,
playMode: PlayMode.Alternate,
expectedFrameRateRange: {
min: 20,
max: 120,
expected: 90,
}
})
2. 共享元素转场
typescript
// PageOne.ets
Button('动画1')
.onClick(() => {
CustomTransition.getInstance().registerNavParam(this.pageId,
(isPush: boolean, isExit: boolean) => {
this.myScale = isExit ? 1 : 1.2;
},
(isPush: boolean, isExit: boolean) => {
this.myScale = isExit ? 1.2 : 1;
},
(isPush: boolean, isExit: boolean) => {
this.myScale = 1;
}, 200);
this.pageInfos.pushPathByName('pageThree', null)
})
八、实战案例
1. 登录界面
scss
Column({ space: 20 }) {
Image($r('app.media.logo'))
.width(100)
Text('登录界面')
.fontSize(24)
.fontWeight(700)
Text('登录账号以使用更多服务')
.fontColor(Color.Gray)
.fontSize(14)
TextInput({ placeholder: '账号' })
.backgroundColor('#ffffff')
.width('80%')
.height(40)
TextInput({ placeholder: '密码', type: InputType.Password })
.backgroundColor('#ffffff')
.width('80%')
.height(40)
Row() {
Text('短信验证码登录')
.fontColor('#3172f3')
Text('忘记密码')
.fontColor('#3172f3')
}
.width('80%')
.justifyContent(FlexAlign.SpaceBetween)
Button('登录')
.width('80%')
.height(40)
.backgroundColor('#007AFF')
.fontColor(Color.White)
Text('注册账号')
.fontColor('#3172f3')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
.backgroundColor('#eff1f3')
2. 可拖拽排序网格组件
核心数据结构:
less
@State numbers: number[] = [] // 网格中显示的数据
@State row: number = 2 // 网格列数
@State lastIndex: number = 0 // 数组最后一个元素的索引
@State dragItem: number = -1 // 当前被拖拽的元素
@State offsetX/offsetY: number = 0 // 拖拽元素的位移
private isUpdating: boolean = false // 是否正在更新
private lastEvent: GestureEvent | null = null // 最新的手势事件
布局实现:
scss
Grid(this.scroller) {
ForEach(this.numbers, (item: number) => {
GridItem() {
Text(item + '')
.fontSize(16)
.width('100%')
.textAlign(TextAlign.Center)
.height(136)
.borderRadius(10)
.backgroundColor(0xFFFFFF)
}
// 其他属性和手势处理...
}
}
.columnsTemplate(this.str) // 设置多列布局
拖拽实现:
kotlin
.gesture(
GestureGroup(GestureMode.Sequence,
PanGesture({
fingers: 1,
direction: null,
distance: 0
})
.onActionStart(() => {
this.dragItem = item
this.dragRefOffsetx = 0
this.dragRefOffsety = 0
this.isUpdating = true
this.startUpdateLoop()
})
.onActionUpdate((event: GestureEvent) => {
// 只保存最新的事件,不直接更新UI
this.lastEvent = event
})
.onActionEnd(() => {
this.isUpdating = false
this.stopSmoothScroll()
animateTo({
curve: curves.interpolatingSpring(0, 1, 400, 38)
}, () => {
this.dragItem = -1
})
// 其他重置逻辑...
})
)
)
九、性能优化
1. 布局性能优化
- 精简节点数:减少不必要的嵌套,提高渲染效率
- 合理控制元素显示隐藏:减少不必要的布局重排
- 设置合适的宽高:避免过度绘制和布局抖动
2. 长列表优化
- 使用
LazyForEach
替代ForEach
,实现按需加载 - 设置合理的
cachedCount
,预加载可见区域附近的项 - 避免在列表项中使用复杂计算或频繁状态更新
十、图片处理
1. 截图功能
组件截图:
javascript
import { componentSnapshot } from '@kit.ArkUI';
import { image } from '@kit.ImageKit';
componentSnapshot.get("target", (error: Error, pixmap: image.PixelMap) => {
if (error) {
console.log("error: " + JSON.stringify(error))
return;
}
// 获取到截取的图片
this.pixmap = pixmap
})
长截图:
kotlin
// 循环滚动并拼接截图
const snipTimes = Math.ceil(this.h5Height / this.webHeight);
for (let i = 0; i < snipTimes; i++) {
const curSnip = await componentSnapshot.get(Constants.WEB_ID);
// 最后一次截图需要特殊处理,去除重复部分
if (i === lastTime) {
logger.info(TAG, `The last snapshot image height ${leftoverHeight}`);
await curSnip.crop(cropLeftover);
offCanvasCtx.drawImage(curSnip, 0, this.webHeight * i, this.webWidth, leftoverHeight);
} else {
offCanvasCtx.drawImage(curSnip, 0, this.webHeight * i, this.webWidth, this.webHeight);
}
// Web通过webviewController实现滚动
}
2. 去水印工具推荐
- 一键改图:深度适配鸿蒙系统,提供智能去水印功能
- 视频抠图:支持图片和视频去水印,提供多种去水印方法
- AI去水印:全自动智能处理,支持批量处理