当前位置:   article > 正文

鸿蒙开发HarmonyOS NEXT (四) 熟悉ArkTs (下)_鸿蒙next rotate

鸿蒙next rotate

一、动画

1、属性动画

animation,可以通过配置动画时间duration等参数,实现移动时的平滑过度

写了个小鱼游动的小案例

  1. @Entry
  2. @Component
  3. struct ActionPage {
  4. @State fish: Resource = $r('app.media.fish_right') //小鱼图片
  5. @State fishX: number = 200 //初始化小鱼横坐标
  6. @State fishY: number = 100 //初始化小鱼纵坐标
  7. build() {
  8. Stack(){ //层叠布局组件
  9. Image($r('app.media.fish_back')).width('100%').height('100%') //背景
  10. RelativeContainer() {
  11. Image(this.fish) //小鱼
  12. .position({
  13. x: this.fishX - 30,
  14. y: this.fishY - 40
  15. })
  16. .rotate({
  17. angle: 0,
  18. centerX: "50%",
  19. centerY: "50%"
  20. })
  21. .width(40)
  22. .height(40)
  23. .animation({
  24. duration: 500, //动画时长,单位毫秒
  25. curve: Curve.EaseInOut
  26. })
  27. Row() { //操作区
  28. Button('←').backgroundColor('#20101010')
  29. .onClick(() => {
  30. animateTo(
  31. { duration: 500 },
  32. () => {
  33. this.fishX -= 20
  34. this.fish = $r('app.media.fish_left')
  35. }
  36. )
  37. })
  38. Column({ space: 40 }) {
  39. Button('↑').backgroundColor('#20101010')
  40. .onClick(() => {
  41. this.fishY -= 20
  42. })
  43. Button('↓').backgroundColor('#20101010')
  44. .onClick(() => {
  45. this.fishY += 20
  46. })
  47. }
  48. Button('→').backgroundColor('#20101010')
  49. .onClick(() => {
  50. animateTo(
  51. { duration: 500 },
  52. () => {
  53. this.fishX += 20
  54. this.fish = $r('app.media.fish_right')
  55. }
  56. )
  57. })
  58. }
  59. .height(240)
  60. .width(240)
  61. .justifyContent(FlexAlign.Center)
  62. .position({x:0,y:120})
  63. }
  64. .height('100%')
  65. .width('100%')
  66. }
  67. }
  68. }

2、组件转场动画

组件插入或者移除时的动画,通过transition属性来配置

可修改上面的小鱼案例,添加小鱼入场动画

通过isBegin变量控制小鱼组件的加载

官网动画相关文档,可以多看看

应用开发导读-基础入门 | 华为开发者联盟 (huawei.com)

3、摇杆扩展小案例

改造上述小鱼游戏案例,将移动操作区域改成摇杆控制

思路:

1、定义摇杆区域,大圆套小圆

2、根据手指移动计算出小球移动,并且不超出大圆

3、根据小球移动角度,和小鱼移动速度,计算出小鱼的角度和最终坐标

ps:本案例是根据B站 黑马程序员_鸿蒙课程案例写的,可以帮助理解

  1. import { curves } from '@kit.ArkUI'
  2. @Entry
  3. @Component
  4. struct ActionPage {
  5. @State fish: Resource = $r('app.media.fish_right')
  6. //小鱼坐标
  7. @State fishX: number = 200
  8. @State fishY: number = 100
  9. //小鱼角度
  10. @State angle: number = 0
  11. //开始游戏
  12. @State isBegin: boolean = false
  13. // 摇杆中心区域坐标
  14. private centerX: number = 120
  15. private centerY: number = 120
  16. //大、小圈半径
  17. private maxRadius: number = 100
  18. private radius: number = 20
  19. //摇杆小球的初始位置
  20. @State positionX: number = this.centerX;
  21. @State positionY: number = this.centerY;
  22. // 角度正弦和余弦
  23. sin: number = 0
  24. cos: number = 0
  25. //小鱼的移动速度
  26. speed: number = 0
  27. //任务id
  28. taskId: number = -1
  29. build() {
  30. Stack() {
  31. Image($r('app.media.fish_back')).width('100%').height('100%')
  32. RelativeContainer() {
  33. if (!this.isBegin) {
  34. Button('开始游戏')
  35. .onClick(() => {
  36. animateTo(
  37. { duration: 1000 },
  38. () => {
  39. this.isBegin = true
  40. }
  41. )
  42. })
  43. .position({ x: 335, y: 130 })
  44. } else {
  45. Image(this.fish)
  46. .position({
  47. x: this.fishX - 30,
  48. y: this.fishY - 40
  49. })
  50. .rotate({
  51. angle: this.angle,
  52. centerX: "50%",
  53. centerY: "50%"
  54. })
  55. .width(40)
  56. .height(40)
  57. .animation({
  58. duration: 500, //动画时长,单位毫秒
  59. curve: Curve.EaseInOut
  60. })
  61. .transition({
  62. type: TransitionType.Insert,
  63. opacity: 0,
  64. translate: { x: -220 }
  65. })
  66. }
  67. //摇杆
  68. Row() {
  69. Circle({ width: this.maxRadius * 2, height: this.maxRadius * 2 })
  70. .fill('#20101010')
  71. .position({ x: this.centerX - this.maxRadius, y: this.centerY - this.maxRadius })
  72. Circle({ width: this.radius * 2, height: this.radius * 2 })
  73. .fill('#20101010')
  74. .position({ x: this.positionX - this.radius, y: this.positionY - this.radius })
  75. }
  76. .onTouch(this.handleTouchEvent.bind(this))
  77. .height(240)
  78. .width(240)
  79. .justifyContent(FlexAlign.Center)
  80. .position({ x: 0, y: 120 })
  81. }
  82. .height('100%')
  83. .width('100%')
  84. }
  85. }
  86. /**处理手指移动*/
  87. handleTouchEvent(event: TouchEvent) {
  88. switch (event.type) {
  89. case TouchType.Up:
  90. //清除定时任务
  91. clearInterval(this.taskId)
  92. this.speed = 0
  93. animateTo(
  94. { curve: curves.responsiveSpringMotion() },
  95. () => {
  96. this.positionX = this.centerX
  97. this.positionY = this.centerY
  98. }
  99. )
  100. this.angle = 0
  101. break;
  102. case TouchType.Down:
  103. //开始定时任务,为了保证按下时小鱼坐标的持续变化
  104. this.taskId = setInterval(() => {
  105. this.fishX += this.speed * this.cos
  106. this.fishY += this.speed * this.sin
  107. }, 40)
  108. break;
  109. case TouchType.Move:
  110. //1、获取手指坐标
  111. let x = event.touches[0].x
  112. let y = event.touches[0].y
  113. //2、手指与中心点的坐标差值
  114. let vx = x - this.centerX
  115. let vy = y - this.centerY
  116. //3、手指和中心的连线与X轴正半轴的夹角
  117. let angles = Math.atan2(vy, vx)
  118. //4、手指与中心的的距离
  119. let distance = this.getDistance(vx, vy)
  120. //5、摇杆小球的坐标
  121. this.cos = Math.cos(angles)
  122. this.sin = Math.sin(angles)
  123. animateTo(
  124. { curve: curves.responsiveSpringMotion() },
  125. () => {
  126. this.positionX = this.centerX + distance * this.cos
  127. this.positionY = this.centerY + distance * this.sin
  128. //小鱼转向角度
  129. if (Math.abs(angles * 2) < Math.PI) {
  130. this.fish = $r('app.media.fish_right')
  131. } else {
  132. this.fish = $r('app.media.fish_left')
  133. angles = angles < 0 ? angles + Math.PI : angles - Math.PI
  134. }
  135. //修改小鱼的坐标
  136. this.angle = angles * 100 / Math.PI
  137. this.speed = 5
  138. }
  139. )
  140. break;
  141. }
  142. }
  143. //已知直角边,计算斜边长
  144. getDistance(x: number, y: number) {
  145. let d = Math.sqrt(x * x + y * y)
  146. return Math.min(d, this.maxRadius)
  147. }
  148. }

二、stage模型

1、基本概念

stage是一种应用模型

应用模型:系统为开发者提供的应用程序必备的组件和运行机制。相当于一个模板,基于统一的模型进行应用开发,使应用开发更简单、高效

目前有两种应用模型:FA 和 Stage

此处,我们先了解stage,它由于提供了AbilityStage、WindowStage等类作为应用组件和Window窗口的“舞台”,因此得名

2、应用配置文件

有两种:全局配置app.json5、模块的配置modle.json5

应用配置文件_鸿蒙官网有对配置中各个属性的详细描述,查询很方便

3、UIAbility生命周期

ForegroundBackground状态分别在UIAbility实例切换至前台和切换至后台时触发

在代码里可以找到对应描述

可以试着在日志中查看生命周期的打印顺序

4、页面及组件的生命周期

注意页面生命周期函数得在像@entry这样修饰的页面使用

另外两种aboutToAppear、aboutToDisappear则可以在自定义组件中使用

  1. aboutToAppear(): void {
  2. console.log("组件加载时触发")
  3. }
  4. onPageShow(): void {
  5. console.log("页面每次显示时触发一次,
  6. 包括路由过程、应用进入前台等场景,仅@Entry装饰的自定义组件生效")
  7. }
  8. onBackPress(): boolean | void {
  9. console.log("用户点击返回按钮时触发")
  10. }
  11. onPageHide(): void {
  12. console.log("页面隐藏,应用进入后台")
  13. }
  14. aboutToDisappear(): void {
  15. console.log("组件销毁时触发")
  16. }

三、网络连接

1、http请求数据

可参考HTTP数据请求-鸿蒙官方文档

官网文档描述的非常细致,包含了使用案例和对应的具体参数含义

还是常规步骤,先引入再使用即可

  1. // 引入包名
  2. import { http } from '@kit.NetworkKit';
  3. // 引入返回报错类
  4. import { BusinessError } from '@kit.BasicServicesKit';
  1. // 每一个httpRequest对应一个HTTP请求任务,不可复用
  2. let httpRequest = http.createHttp();
  1. // 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
  2. httpRequest.on('headersReceive', (header: Object) => {
  3. console.info('header: ' + JSON.stringify(header));
  4. });
  5. class Header {
  6. public contentType: string;
  7. constructor(contentType: string) {
  8. this.contentType = contentType;
  9. }
  10. }
  1. httpRequest.request(
  2. // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
  3. "EXAMPLE_URL",
  4. {
  5. method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
  6. // 当使用POST请求时此字段用于传递请求体内容,具体格式与服务端协商确定,可以是字符串或者对象
  7. extraData: 'data to send',
  8. expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
  9. usingCache: true, // 可选,默认为true
  10. priority: 1, // 可选,默认为1
  11. // 开发者根据自身业务需要添加header字段
  12. header: new Header('application/json'),
  13. readTimeout: 60000, // 可选,默认为60000ms
  14. connectTimeout: 60000, // 可选,默认为60000ms
  15. },
  16. (err: BusinessError, data: http.HttpResponse) => {
  17. if (!err) {
  18. // data.result为HTTP响应内容,可根据业务需要进行解析
  19. console.info('Result:' + JSON.stringify(data.result));
  20. // 取消订阅HTTP响应头事件
  21. httpRequest.off('headersReceive');
  22. // 当该请求使用完毕时,开发者务必调用destroy方法主动销毁该JavaScript Object。
  23. httpRequest.destroy();
  24. } else {
  25. console.info('error:' + JSON.stringify(err));
  26. // 取消订阅HTTP响应头事件
  27. httpRequest.off('headersReceive');
  28. // 当该请求使用完毕时,开发者务必调用destroy方法主动销毁该JavaScript Object。
  29. httpRequest.destroy();
  30. }
  31. });

2、第三方库axios

因为axios是第三方库,所以需要三方库的包管理工具ohpm来管理

2.1  检查ohpm

终端中输入命令 

ohpm -v

可以看的ohmp的版本号

(注意:比较旧的版本可能需要自己下载安装ohmp,但版本为“HarmonyOS NEXT Developer Beta1”,版本文档更新于2024-06-25的肯定已经自动配置好了的)

2.2  下载安装axios

也是可以参考OpenHarmony三方库中心仓

里面包含了常用三方库的配置和使用说明

1、module.json5中要配置允许访问网络

2、输入安装命令:ohpm install @ohos/axios

3、安装完成,使用axios

  1. import axios from '@ohos/axios'
  2. interface userInfo{
  3. id: number
  4. name: string,
  5. phone: number
  6. }
  7. // 向给定ID的用户发起请求
  8. axios.get<userInfo, AxiosResponse<userInfo>, null>('/user?ID=12345')
  9. .then((response: AxiosResponse<userInfo>)=> {
  10. // 处理成功情况
  11. console.info("id" + response.data.id)
  12. console.info(JSON.stringify(response));
  13. })
  14. .catch((error: AxiosError)=> {
  15. // 处理错误情况
  16. console.info(JSON.stringify(error));
  17. })
  18. .then(()=> {
  19. // 总是会执行
  20. });

四、数据持久化

概念:将内存中的数据通过文件或数据库的形式保存到设备上。目的是为了常用的数据能方便的存取

1、用户首选项

全局唯一存储的地方,轻量级的,所以不能存放太多数据,也不支持通过配置加密,一般存放“字体大小设置、是否开启夜间模式”等

通过用户首选项实现数据持久化-官网文档

2、关系型数据库

存储包含复杂关系数据,比如一个班级的学生信息,需要包括姓名、学号、各科成绩等

通过关系型数据库实现数据持久化-官网文档


六、通知

可借助Notification Kit将应用产生的通知直接在客户端本地推送给用户,本地通知根据通知类型及发布场景会产生对应的铃声、震动、横幅、锁屏、息屏、通知栏提醒和显示。

Notification Kit简介-Notification Kit(用户通知服务)-应用服务 | 华为开发者联盟 (huawei.com)

  • 基础通知: 发送短信息、提示信息等
  • 进度条通知:应用于文件下载、事务处理进度显示
  • 通知行为意图:当发布通知时,如果期望用户可以通过点击通知栏拉起目标应用组件或发布公共事件

详细使用可参考发布通知-官网文档

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/986671
推荐阅读
相关标签
  

闽ICP备14008679号