• HarmonyOS Codelab 优秀样例——溪村小镇(ArkTS)


    一、介绍

    溪村小镇是一款展示溪流背坡村园区风貌的应用,包括园区内的导航功能,小火车行车状态查看,以及各区域的风景展览介绍,主要用于展示HarmonyOS的ArkUI能力和动画效果。具体包括如下功能:

    1. 打开应用时进入启动页,启动页轮播展示溪村小镇风景图,之后进入应用首页。
    2. 在首页的“地图浏览”标签页,可以拖动和缩放查看地图,并查找相应地标建筑。
    3. 在首页的“区域导览”标签页,可以上下滑动查看溪村小镇不同区域的卡片,点击卡片可以进入对应的区域详情页并查看区域的详细介绍和高清建筑风景图。
    4. 在首页的“小火车”标签页,可以查看溪村小火车的运行路线图。

    相关概念

    • Tabs组件:通过页签进行内容视图切换的容器组件,每个页签对应一个内容视图。
    • List组件:列表包含一系列相同宽度的列表项,包含子组件ListItem。
    • 点击手势:支持单击、双击和多次点击事件的识别。
    • 拖动手势:用于触发拖动手势事件,滑动的最小距离为5vp时拖动手势识别成功。
    • 捏合手势:用于触发捏合手势事件,触发捏合手势的最少手指为2指,最大为5指,最小识别距离为3vp。
    • 属性动画:组件的某些通用属性变化时,可以通过属性动画实现渐变过渡效果,提升用户体验。
    • 自定义弹窗:通过CustomDialogController类显示自定义弹窗。使用弹窗组件时,可优先考虑自定义弹窗,便于自定义弹窗的样式与内容。
    • Canvas画布:用于自定义绘制图形。

    完整示例

    gitee源码地址

    二、环境搭建

    我们首先需要完成HarmonyOS开发环境搭建,可参照如下步骤进行。

    软件要求

    硬件要求

    • 设备类型:华为手机或运行在DevEco Studio上的华为手机设备模拟器。
    • HarmonyOS系统:3.1.0 Developer Release。

    环境搭建

    1. 安装DevEco Studio,详情请参考下载和安装软件
    2. 设置DevEco Studio开发环境,DevEco Studio开发环境需要依赖于网络环境,需要连接上网络才能确保工具的正常使用,可以根据如下两种情况来配置开发环境:如果可以直接访问Internet,只需进行下载HarmonyOS SDK操作。
      1. 如果网络不能直接访问Internet,需要通过代理服务器才可以访问,请参考配置开发环境
    3. 开发者可以参考以下链接,完成设备调试的相关配置:使用真机进行调试
      1. 使用模拟器进行调试

    三、代码结构解读

    本篇Codelab只对核心代码进行讲解,对于完整代码,我们会在gitee中提供。

    1. ├──entry/src/main/ets                  // 代码区
    2. │  ├──common
    3. │  │  ├──bean
    4. │  │  │  ├──AddressItem.ets              // 地图地标类 
    5. │  │  │  ├──BottomTabsItem.ets           // 底部标签类
    6. │  │  │  ├──PositionItem.ets             // 搜索面板地标类
    7. │  │  │  ├──TrainMap.ets                 // 小火车数据类
    8. │  │  │  └──ZonesItem.ets          // 区域介绍类
    9. │  │  ├──constants 
    10. │  │  │  ├──CommonConstants.ets          // 公共常量类
    11. │  │  │  └──ZonesConstants.ets           // 区域常量类 
    12. │  │  ├──images
    13. │  │  └──utils
    14. │  │     ├──Animation.ets                // 区域详情动效类          
    15. │  │     ├──DeviceScreen.ets             // 获取设备信息类
    16. │  │     ├──Geography.ets                // 地理坐标转换工具类
    17. │  │     ├──Logger.ets                   // 日志打印类
    18. │  │     └──WindowBar.ets                // 沉浸式导航栏
    19. │  ├──control  
    20. │  │  └──MapController.ets               // 地图控制类
    21. │  ├──entryability
    22. │  │  └──EntryAbility.ets          // 程序入口类
    23. │  ├──pages
    24. │  │  ├──IntroductionPage.ets            // 区域详情页
    25. │  │  ├──MainPage.ets                    // 应用首页
    26. │  │  └──Splash.ets                      // 启动页
    27. │  ├──view
    28. │  │  ├──BottomTabsComponent.ets         // 底部标签栏
    29. │  │  ├──BuildListItem.ets               // 区域详情建筑、地理位置ListItem组件
    30. │  │  ├──ImageAnimate.ets                // 区域详情小图滑动组件
    31. │  │  ├──ImageViewComponent.ets          // 查看大图弹窗
    32. │  │  ├──MapComponent.ets                // 地图组件
    33. │  │  ├──StyleListItem.ets               // 区域详情风格信息ListItem组件          
    34. │  │  ├──SubTitleItem.ets                // 区域详情子标题ListItem组件
    35. │  │  ├──SwiperListItem.ets              // 区域详情首图轮播组件
    36. │  │  ├──TrainsComponent.ets             // 小火车轨迹更新
    37. │  │  ├──TrainsTrack.ets                 // 小火车组件
    38. │  │  └──ZonesComponent.ets          // 区域导览组件
    39. │  └──viewmodel
    40. │     ├──ButtonTabsModel.ets             // 底部标签数据
    41. │     ├──MapModel.ets                    // 地图数据及方法
    42. │     ├──SplashModel.ets                 // 启动页数据
    43. │     ├──TrainsMapModel.ets              // 小火车数据及方法
    44. │     └──ZonesViewModel.ets              // 区域介绍信息
    45. └──entry/src/main/resources          // 资源文件目录

    四、应用主页面与沉浸式设计

    4.1 启动页

    应用首次打开会进入启动页。在启动页内分三个时间段(白天、傍晚、晚上),会根据当前时间段轮播展示溪村小镇的优美风景。

    在onWindowStageCreate生命周期中配置启动页入口。

    1. // EntryAbility.ets
    2. onWindowStageCreate(windowStage: window.WindowStage) {
    3. // Main window is created, set main page for this ability
    4.   hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    5.   windowStage.loadContent('pages/Splash', (err, data) => {
    6. if (err.code) {
    7.       hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
    8. return;
    9. }
    10.     hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    11. });
    12. }

    启动页会在aboutToAppear生命周期内初始化轮播图片资源及定时任务,会展示5秒溪村的优美风景,用户可以点击右上角的跳过直接进入应用主页,也可以等5秒结束自动进入应用主页;5秒倒计时结束、用户主动点击跳过或启动页面销毁时都会取消定时器任务。

    1. // Splash.ets
    2. @Entry
    3. @Component
    4. struct Splash {
    5. @State countdown: number = Const.COUNTDOWN;
    6. @State showSwiper: boolean = false;
    7. private swiperController: SwiperController = new SwiperController();
    8. private data: Resource[] = [];
    9. private timer = null;
    10. // 在此生命周期内根据当前时间段分配轮播展示的溪村小镇风景图
    11. aboutToAppear(): void {
    12.     let hours = new Date().getHours();
    13. if (hours >= Const.MORNING_TIME && hours < Const.EVENING_TIME) {
    14. this.data = splashImages.day;
    15. } else {
    16. ...
    17. }
    18. // 启动画面展示3秒后 轮播展示溪村小镇风景
    19. setTimeout(() => {
    20. this.showSwiper = true;
    21. this.startTiming();
    22. }, Const.SPLASH_DURATION);
    23. }
    24. // 轮播展示溪村小镇风景倒计时5
    25. startTiming() {
    26. this.timer = setInterval(() => {
    27. this.countdown--;
    28. if (this.countdown === 0) {
    29. this.clearTiming();
    30. // 5秒钟后自动跳转到应用首页
    31. this.jumpToMainPage();
    32. }
    33. }, Const.DURATION);
    34. }
    35. // 清理定时器
    36. clearTiming() {
    37. if (this.timer !== null) {
    38. clearInterval(this.timer);
    39. this.timer = null;
    40. }
    41. }
    42. // 跳转到应用首页
    43. jumpToMainPage() {
    44. this.clearTiming();
    45.     router.replaceUrl({
    46.       url: 'pages/MainPage'
    47. });
    48. }
    49. // 页面销毁时清理定时器
    50. aboutToDisappear() {
    51. this.clearTiming();
    52. }
    53. build() {
    54. Column() {
    55. Stack() {
    56. // 轮播展示溪村小镇风景
    57. if (this.showSwiper) {
    58. Swiper(this.swiperController) {
    59. ForEach(this.data, (item: Resource) => {
    60. Image(item)
    61. ...
    62. })
    63. }
    64. .loop(true)
    65. ...
    66. // 轮播倒计时,点击可进入应用主页
    67. Text() {
    68. Span($r('app.string.skip'))
    69. Span(`${this.countdown}`)
    70. }
    71. .onClick(() => this.jumpToMainPage())
    72. ...
    73. })
    74. } else { // 应用启动画面
    75. Image($r('app.media.splash_bg'))
    76. ...
    77. Image($r('app.media.ic_splash'))
    78. ...
    79. Column() {
    80. Text(Const.SPLASH_DES)
    81. ...
    82. Text(Const.SPLASH_WELCOME)
    83. ...
    84. }
    85. }
    86. }
    87. }
    88. ...
    89. }
    90. }

    4.2 应用首页

    应用首页包括三个标签页,分别是“地图浏览”页、“区域导览”页和“小火车”页,效果如图所示:

    该页面使用Tabs组件实现,使用一个自定义的底部标签栏组件来控制选中对应的标签页时的视觉效果。

    1. // MainPage.ets
    2. @Entry
    3. @Component
    4. struct MainPage {
    5. // 当底部标签栏index改变时调用onIndexChange()方法,改变Tabs组件的index
    6. @State @Watch('onIndexChange') bottomTabIndex: number = 1;
    7. private controller: TabsController = new TabsController();
    8. onIndexChange() {
    9. this.controller.changeIndex(this.bottomTabIndex);
    10. }
    11. build() {
    12. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.End, justifyContent: FlexAlign.End }) {
    13. Tabs({ barPosition: BarPosition.Endindex: 1, controller: this.controller }) {
    14. TabContent() {
    15. // “地图浏览”页
    16. Map()
    17. }
    18. TabContent() {
    19. // “区域导览”页
    20. Zones()
    21. }
    22. TabContent() {
    23. // “小火车”页
    24. Trains()
    25. }
    26. }
    27. ...
    28. .onChange((indexnumber) => {
    29. // 当标签页切换时改变底部标签栏组件的index
    30. this.bottomTabIndex = index;
    31. })
    32. // 底部标签栏组件
    33. BottomTabs({ bottomTabIndex: $bottomTabIndex })
    34. }
    35. .width(Const.FULL_PERCENT)
    36. }
    37. }

    五、地图浏览

    地图浏览模块提供了“溪村小镇”的全景地图,方便用户了解“溪村小镇”内部的地理概况。包含以下功能:

    1. 搜索指定类型地标,并在地图上展示。
    2. 通过手势对地图进行操作,包括放大、缩小和拖拽。

    5.1 初始化地图

    地图使用Stack组件实现,地图初始化的宽高是由图片的宽高和地图父组件的宽高计算得出,地图位置由地图宽度和地图父组件计算得出。

    1. // MapComponent.ets
    2. build() {
    3. Stack({ alignContent: Alignment.BottomEnd }) {
    4. Column() {
    5. // 地图组件
    6. Stack({ alignContent: Alignment.TopStart }) {
    7. ...
    8. }
    9. // 地图图片
    10. .backgroundImage($r('app.media.ic_nav_map'))
    11. .backgroundImageSize(ImageSize.Cover)
    12. // 地图宽度
    13. .width(this.mapWidth)
    14. // 地图高度
    15. .height(this.mapHeight)
    16. // 地图左上角位置
    17. .offset({ x: this.mapX, y: this.mapY })
    18. }
    19. ....
    20. .onAreaChange((oldVal: Area, newVal: Area) => {
    21. if (this.screenMapWidth === 0 || this.screenMapHeight === 0) {
    22. // 获取地图父组件宽高
    23. this.screenMapWidth = Number(newVal.width);
    24. this.screenMapHeight = Number(newVal.height);
    25. // 初始化地图组件
    26.         MapController.initMap(this);
    27. }
    28. })
    29. ...
    30. }
    31. }
    32. ...

    地图高度默认为地图父组件高度,地图宽度根据地图原始宽高比得出。

    1. // MapController.ets
    2. initMap(mapContext): void {
    3. this.mapContext = mapContext;
    4. this.mapContext.mapHeight = this.mapContext.screenMapHeight;
    5. // 计算地图宽度
    6. this.mapContext.mapWidth = Const.MAP_WIDTH * this.mapContext.mapHeight / Const.MAP_HEIGHT;
    7. // 设备屏幕默认显示地图中心位置
    8. this.mapContext.mapX = (this.mapContext.screenMapWidth - this.mapContext.mapWidth) / Const.DOUBLE_OR_HALF;
    9. // 计算地图左上角最大移动距离
    10. this.leftTop = [(this.mapContext.screenMapWidth - this.mapContext.mapWidth), 0];
    11. }

    5.2 搜索并展示指定类型地标

    “地图浏览”完成地图初始化后,界面会默认展示查询搜索面板。用户通过搜索框输入指定类型进行搜索,也可以直接点击面板中已展示的类型进行搜索。

    搜索面板为自定义组件CustomPanel,主要由展开/收起图标(Image组件)、搜索栏(Search组件)、地标网格(Grid组件)构成。用户点击地标网格中的网格、通过搜索框搜索指定类型或点击展开/收起图标,都会改变操作面板的显示状态(展示或隐藏)。通过属性动画(animation)可以实现操作面板的渐变过渡效果。

    1. // MapComponent.ets
    2. @Component
    3. struct CustomPanel {
    4. @State positionList: Array = PositionList;
    5. ...
    6. build() {
    7. Column() {
    8. Column() {
    9. Image(this.isDownImage ? $r('app.media.ic_panel_down') : $r('app.media.ic_panel_up'))
    10. .enabled(this.imageEnable)
    11. ...
    12. }
    13. .opacity(this.iconOpacity)
    14. ...
    15. Column() {
    16.     ...
    17. Grid() {
    18. ForEach(this.positionList, (item: PositionItem) => {
    19. GridItem() {
    20. PositionGridView({ positionItem: item })
    21. .enabled(this.imageEnable)
    22. ...
    23. }
    24. }, item => JSON.stringify(item))
    25. }
    26. ...
    27. }
    28. .opacity(this.panelOpacity)
    29. .height(this.panelHeight)
    30. .animation({
    31.         duration: Const.ANIMATION_DURATION,
    32.         curve: Curve.EaseOut,
    33.         iterations: 1,
    34.         playMode: PlayMode.Normal
    35. })
    36. ...
    37. }
    38. ...
    39. }
    40. upAndDown() {
    41. // 配合属性动画实现渐变过渡效果
    42. this.imageEnable = false;
    43. if (this.isDownImage) {
    44. this.panelOpacity = 0;
    45. this.panelHeight = 0;
    46. this.iconOpacity = Const.PANEL_LOW_OPACITY;
    47. } else {
    48. this.panelHeight = Const.PANEL_FULL_HEIGHT;
    49. this.panelOpacity = Const.PANEL_HIGH_OPACITY;
    50. this.iconOpacity = Const.PANEL_HIGH_OPACITY;
    51. }
    52. this.isDownImage = !this.isDownImage;
    53. this.imageEnable = true;
    54. }
    55. }

    通过搜索框或点击网格中的图标对地标进行搜索,并在地图上展示。每种类型的地标均有预置的经纬度数据,根据地标经纬度数据和地图组件宽高计算地标初始位置。

    1. // MapModel.ets
    2. // 根据坐标经纬度和地标信息初始化地标对象
    3. calCoordinateByLonAndLat(geoCoordinates: Array<GeoCoordinates>typenumber, mapContext: any): AddressItem {
    4. this.mapContext = mapContext;
    5. this.data = undefined;
    6. if (!this.addressArray[type - 1]) {
    7. // 初始化地标对象
    8. this.addressArray[type - 1] = new AddressItem(
    9.       mapLandmarksName[type - 1],
    10.       mapLandmarksIcon[type - 1],
    11. // 根据经纬度计算地标在地图中的坐标
    12. this.initLocationData(geoCoordinates),
    13.       mapLandmarksTextColor[type - 1]
    14. );
    15. }
    16. this.data = this.addressArray[type - 1];
    17. return this.data;
    18. }
    19. // MapModel.ets
    20. // 根据地标经纬度和地图宽高获取地标在地图中的初始坐标值
    21. initLocationData(geoCoordinates: Array<GeoCoordinates>): Array<Location> {
    22.   let locations: Array<Location> = [];
    23.   geoCoordinates.forEach((item: GeoCoordinates) => {
    24. // 根据经纬度和地图默认宽高计算地标在地图中的初始坐标值
    25.     let pixelCoordinates = Geography.toPixelCoordinates(item.latitude, item.longitude);
    26. // 根据地图放大倍数计算地标在地图中的水平方向坐标值
    27.     let positionX = pixelCoordinates.coordinateX * this.mapContext.mapWidth / MapController.mapMultiples() /
    28.       Const.MAP_WIDTH;
    29. // 根据地图放大倍数计算地标在地图中的水平方向坐标值
    30.     let positionY = pixelCoordinates.coordinateY / Const.MAP_HEIGHT *
    31. this.mapContext.mapHeight / MapController.mapMultiples();
    32.     locations.push(new Location(positionX, positionY));
    33. })
    34. return locations;
    35. }

    根据获取地标的初始坐标值和地图放大倍数计算地标的的实际坐标值。

    1. // MapModel.ets
    2. calLandmarksPosition(): void {
    3. this.mapContext.data.locations = this.mapContext.data.locations.map((item: Location) => {
    4.     item.positionX = item.oriPositionX * this.mapMultiples() -
    5.       Const.MAP_LANDMARKS_SIZE * Const.MAP_ZOOM_RATIO / Const.DOUBLE_OR_HALF;
    6.     item.positionY = item.oriPositionY * this.mapMultiples() -
    7.       Const.MAP_LANDMARKS_SIZE * Const.MAP_ZOOM_RATIO;
    8. return item;
    9. })
    10. }

    地标初始化完成之后,默认将第一个地标展示在设备屏幕范围内(水平方向居中)。

    1. // MapController.ets
    2. setFirstLandmarksCenter(): void {
    3.   let locations = this.mapContext.data.locations;
    4. if (locations.length > 0) {
    5. // 计算地图左上角水平方向坐标
    6. this.mapContext.mapX = this.mapContext.screenMapWidth / Const.DOUBLE_OR_HALF - locations[0].positionX;
    7. // 判断地图左上角是否超出边界
    8. if (this.mapContext.mapX > 0) {
    9. this.mapContext.mapX = 0;
    10. }
    11. if (this.mapContext.mapX < (this.mapContext.screenMapWidth - this.mapContext.mapWidth)) {
    12. this.mapContext.mapX = this.mapContext.screenMapWidth - this.mapContext.mapWidth;
    13. }
    14. // 判断地图右下角是否超出边界
    15. this.mapContext.mapY = this.mapContext.screenMapHeight / Const.DOUBLE_OR_HALF - locations[0].positionY;
    16. if (this.mapContext.mapY > 0) {
    17. this.mapContext.mapY = 0;
    18. }
    19. if (this.mapContext.mapY < (this.mapContext.screenMapHeight - this.mapContext.mapHeight)) {
    20. this.mapContext.mapY = this.mapContext.screenMapHeight - this.mapContext.mapHeight;
    21. }
    22. }
    23. }

    5.3 使用手势操作地图

    操作地图的手势由捏合手势(PinchGesture)、点击手势(TapGesture)、平移手势(PanGesture)组合而成,可放大、缩小和移动地图。

    1. // MapComponent.ets
    2. build() {
    3. Stack({ alignContent: Alignment.BottomEnd }) {
    4. Column() {
    5. ...
    6. }
    7. ...
    8. // 地图父组件绑定手势事件
    9. .gesture(
    10. GestureGroup(GestureMode.Exclusive,
    11. // 捏合手势,放大缩小地图
    12. PinchGesture({ fingers: Const.MAP_FINGER_COUNT })
    13. .onActionUpdate((event: GestureEvent) => {
    14.             MapController.pinchUpdate(event);
    15. })
    16. .onActionEnd(() => {
    17.             MapController.pinchEnd();
    18. }),
    19. // 点击手势,放大地图
    20. TapGesture({ count: Const.MAP_FINGER_COUNT })
    21. .onAction(() => {
    22.             MapController.tapAction();
    23. }),
    24. // 平移手势,拖动地图
    25. PanGesture(this.panOption)
    26. .onActionUpdate((event: GestureEvent) => {
    27.             MapController.panUpdate(event);
    28. })
    29. .onActionEnd(() => {
    30.             MapController.panEnd();
    31. })
    32. )
    33. )
    34. ...
    35. }
    36. }

    捏合手势是通过双指向外拨动放大地图、向内捏合缩小地图,每次将地图放大或缩小1.1倍,最多放大4次。当地图缩放到初始化时的大小后不再进行缩小,地图进行缩放时总是以地图所在屏幕中心位置进行缩放,效果如图所示:

    1. // MapController.ets
    2. pinchUpdate(event: GestureEvent): void {
    3. // 获取当前捏合手势的数值
    4.   let scale = parseFloat(event.scale.toFixed(Const.MAP_SCALE_ACCURACY));
    5.   let ratio = 1;
    6. // 防止手指一直按压屏幕操作
    7. if (this.previousScale !== scale) {
    8. // 向内捏合手势
    9. if (event.scale < 1) {
    10.       ratio = 1 / Const.MAP_ZOOM_RATIO;
    11. this.pinchCount--;
    12. } else {
    13. // 向外拨动手势
    14.       ratio = Const.MAP_ZOOM_RATIO;
    15. this.pinchCount++;
    16. }
    17. // 只允许放大4
    18. if (this.pinchCount > Const.ZOOM_MAX_TIMES) {
    19. this.pinchCount = Const.ZOOM_MAX_TIMES;
    20. return;
    21. }
    22. // 防止无限缩小
    23. if (this.pinchCount < 0) {
    24. this.pinchCount = 0;
    25. return;
    26. }
    27. // 根据缩放倍数,实时计算地图宽高
    28. this.mapContext.mapWidth *= ratio;
    29. this.mapContext.mapHeight *= ratio;
    30. // 以当前设备中心对地图进行缩放
    31.     let offsetX = (1 - ratio) * (this.mapContext.screenMapWidth /
    32.       Const.DOUBLE_OR_HALF - this.mapContext.mapX);
    33.     let offsetY = (1 - ratio) * (this.mapContext.mapHeight /
    34.       Const.MAP_ZOOM_RATIO / Const.DOUBLE_OR_HALF - this.mapContext.mapY);
    35. this.mapContext.mapX += offsetX;
    36. this.mapContext.mapY += offsetY;
    37. // 重新计算地标的坐标值
    38. this.calLandmarksPosition();
    39. // 判断地图是否超出边界
    40. this.zoomOutCheck();
    41. }
    42. this.previousScale = scale;
    43. }

    地图缩放过程中根据当前地图宽高对地标进行位置偏移。

    1. // MapController.ets
    2. calLandmarksPosition(): void {
    3.   this.mapContext.data.locations = this.mapContext.data.locations.map((item: Location=> {
    4.     item.positionX = item.oriPositionX * this.mapMultiples() -
    5.       Const.MAP_LANDMARKS_SIZE * Const.MAP_ZOOM_RATIO / Const.DOUBLE_OR_HALF;
    6.     item.positionY = item.oriPositionY * this.mapMultiples() -
    7.       Const.MAP_LANDMARKS_SIZE * Const.MAP_ZOOM_RATIO;
    8.     return item;
    9.   })
    10. }

    地图移动过程中根据左上角坐标判断是否超出临界点,若地图缩小超出临界点,就以临界点位置进行地图缩小。

    1. // MapController.ets
    2. zoomOutCheck(): void {
    3. if (this.mapContext.mapX > 0) {
    4. this.mapContext.mapX = 0;
    5. }
    6. if (this.mapContext.mapY > 0) {
    7. this.mapContext.mapY = 0;
    8. }
    9. if ((this.mapContext.mapX + this.mapContext.mapWidth) < this.mapContext.screenMapWidth) {
    10. this.mapContext.mapX = this.mapContext.screenMapWidth - this.mapContext.mapWidth;
    11. }
    12. if ((this.mapContext.mapY + this.mapContext.mapHeight) < (this.mapContext.mapHeight / this.mapMultiples())) {
    13. this.mapContext.mapY = this.mapContext.mapHeight / this.mapMultiples() - this.mapContext.mapHeight;
    14. }
    15. }

    点击手势通过双击地图组件放大地图(缩小地图只能通过捏合手势),每次将地图放大1.1倍,最多放大4次,地图进行放大时总是以地图所在屏幕中心位置进行放大,效果如图所示:

    1. // MapController.ets
    2. tapAction(): void {
    3. if (++this.pinchCount > Const.ZOOM_MAX_TIMES) {
    4. this.pinchCount = Const.ZOOM_MAX_TIMES;
    5. return;
    6. }
    7. this.mapContext.mapWidth *= Const.MAP_ZOOM_RATIO;
    8. this.mapContext.mapHeight *= Const.MAP_ZOOM_RATIO;
    9.   let offsetX = (1 - Const.MAP_ZOOM_RATIO) *
    10. (this.mapContext.screenMapWidth / Const.DOUBLE_OR_HALF - this.mapContext.mapX);
    11.   let offsetY = (1 - Const.MAP_ZOOM_RATIO) * (this.mapContext.mapHeight /
    12.     Const.MAP_ZOOM_RATIO / Const.DOUBLE_OR_HALF - this.mapContext.mapY);
    13. this.mapContext.mapX += offsetX;
    14. this.mapContext.mapY += offsetY;
    15. // 重新计算地标的坐标
    16. this.calLandmarksPosition();
    17. // 计算地图左上角可移动范围
    18.   let minX = (this.mapContext.screenMapWidth - this.mapContext.mapWidth);
    19.   let minY = this.mapContext.mapHeight / this.mapMultiples() - this.mapContext.mapHeight;
    20. this.leftTop = [minX, minY];
    21. }

    平移手势通过单指拖动地图组件移动地图,当地图位于边界时,禁止拖动。效果如图所示:

    1. // MapController.ets
    2. // 根据手指滑动距离设置地图滑动距离
    3. panUpdate(event: GestureEvent): void {
    4.   let panX = parseInt(event.offsetX.toFixed(0));
    5.   let panY = parseInt(event.offsetY.toFixed(0));
    6. if ((this.panX !== panX) || (this.panY !== panY)) {
    7. this.panCheck(panX, panY);
    8. }
    9. this.panX = panX;
    10. this.panY = panY;
    11. }
    12. // 计算地图滑动距离并判断临界点
    13. panCheck(panX, panY): void {
    14.   let mapPanX = panX - this.panX;
    15.   let mapPanY = panY - this.panY;
    16. this.mapContext.mapX += mapPanX;
    17. this.mapContext.mapY += mapPanY;
    18. if (this.mapContext.mapX < this.leftTop[0]) {
    19. this.mapContext.mapX = this.leftTop[0];
    20. }
    21. if (this.mapContext.mapX > 0) {
    22. this.mapContext.mapX = 0;
    23. }
    24. if (this.mapContext.mapY < this.leftTop[1]) {
    25. this.mapContext.mapY = this.leftTop[1];
    26. }
    27. if (this.mapContext.mapY > 0) {
    28. this.mapContext.mapY = 0;
    29. }
    30. }

    六、区域导览

    6.1 区域导览卡片

    区域导览页展示了一个由各个区域导览卡片组成的可上下滑动的轮播图,效果如图所示:

    轮播效果是Stack组件结合拖动手势来实现的,根据手势拖动的距离来判断是否需要切换图片,同时根据手势拖动的方向来决定是切换到上一张还是下一张图片。在图片切换的过程中,会根据图片和最上层图片的下标的差值,来计算它的模糊度、透明度、纵向偏移量、宽度等属性值。

    1. // ZonesComponent.ets
    2. Stack() {
    3. ForEach(this.zonesList, (item: ZonesItem, indexnumber) => {
    4. Row() {
    5. Image(item.thumbnail)
    6. ...
    7. .shadow({
    8.           radius: Const.SHADOW_RADIUS,
    9.           color: `rgba(0,0,0,0.3)`,
    10.           offsetY: Const.SHADOW_RADIUS / Const.DOUBLE_NUM
    11. })
    12. // 图片透明度
    13. .opacity(1 - Math.min(ZoneConst.HALF_COUNT,
    14.           Math.abs(this.getImgCoefficients(index))) * ZoneConst.OPACITY_COEFFICIENTS)
    15. }
    16. // 图片宽度
    17. .width(index != this.aheadIndex && this.getImgCoefficients(index) === 0 ?
    18.       Const.SWIPER_DEFAULT_WIDTH :
    19.       `${ZoneConst.ITEM_WIDTH - ZoneConst.OFFSET_COEFFICIENTS * Math.abs(this.getImgCoefficients(index))}%`)
    20. .offset({ x: 0, y: this.getOffSetY(index) })
    21. .zIndex(index != this.aheadIndex && this.getImgCoefficients(index) === 0 ?
    22. 0 : ZoneConst.HALF_COUNT - Math.abs(this.getImgCoefficients(index)))
    23. // 毛玻璃效果
    24. .blur(ZoneConst.OFFSET_COEFFICIENTS * Math.abs(this.getImgCoefficients(index)))
    25. }, (item: ZonesItem) => JSON.stringify(item))
    26. }
    27. .gesture(
    28. // 添加手势,通过手势实现图片的动态效果
    29. PanGesture({ direction: PanDirection.Vertical })
    30. .onActionStart((event: GestureEvent) => {
    31. this.changedIndex = false;
    32. this.handlePanGesture(event.offsetY);
    33. })
    34. .onActionUpdate((event: GestureEvent) => {
    35. this.handlePanGesture(event.offsetY);
    36. })
    37. .onActionEnd(() => {
    38. animateTo({
    39.         duration: Const.SWIPER_DURATION,
    40. }, () => {
    41. this.marginBottom = 0;
    42. });
    43. })
    44. ...
    45. )
    46. // 计算图片和最上方图片的下标相对差值
    47. getImgCoefficients(indexnumber): number {
    48.   let coefficient = this.aheadIndex - index;
    49.   let tempCoefficient = Math.abs(coefficient);
    50. if (tempCoefficient <= ZoneConst.HALF_COUNT) {
    51. return coefficient;
    52. }
    53.   let dataLength = this.zonesList.length;
    54.   let tempOffset = dataLength - tempCoefficient;
    55. if (tempOffset <= ZoneConst.HALF_COUNT) {
    56. if (coefficient > 0) {
    57. return -tempOffset;
    58. }
    59. return tempOffset;
    60. }
    61. return 0;
    62. }
    63. // 计算图片y轴方法的偏移量
    64. getOffSetY(indexnumber): number {
    65.   let offsetIndex = this.getImgCoefficients(index);
    66.   let tempOffset = Math.abs(offsetIndex);
    67.   let offsetY = this.marginBottom / (tempOffset + 1);
    68. if (tempOffset === 1) {
    69.     offsetY += -offsetIndex * ZoneConst.MAX_OFFSET_Y;
    70. } else if (tempOffset === ZoneConst.HALF_COUNT) {
    71.     offsetY += -offsetIndex * (ZoneConst.MAX_OFFSET_Y - ZoneConst.OFFSET_COEFFICIENTS);
    72. }
    73. return offsetY;
    74. }
    75. // 动态滚动切换最上方图片
    76. startAnimation(isUp: boolean): void {
    77. animateTo({
    78.     duration: Const.SWIPER_DURATION,
    79. }, () => {
    80.     let dataLength = this.zonesList.length;
    81.     let tempIndex = isUp ? this.aheadIndex + 1 : dataLength + this.aheadIndex - 1;
    82. this.aheadIndex = tempIndex % dataLength;
    83. this.marginBottom = 0;
    84. });
    85. }
    86. // 判断是否需要切换最上方图片
    87. handlePanGesture(offsetY: number): void {
    88. if (Math.abs(offsetY) < ZoneConst.MAX_MOVE_OFFSET) {
    89. this.marginBottom = offsetY;
    90. } else {
    91. if (this.changedIndex) {
    92. return;
    93. }
    94. this.changedIndex = true;
    95. this.startAnimation(offsetY < 0);
    96. }
    97. }

    在区域导览页点击跳转到区域详情页时,使用pageTransition函数实现了界面跳转过程中的动画效果,效果如图所示:

    为实现图中效果,需要在区域导览所在的@Entry界面和详情页所在的@Entry界面里使用pageTransition函数来改变他们入场和出场时的方向、缩放大小和透明度等。

    1. // MainPage.ets
    2. @Entry
    3. @Component
    4. struct MainPage {
    5. pageTransition() {
    6. PageTransitionEnter({ duration: Const.SHARED_DURATION })
    7. .slide(SlideEffect.Top);
    8. PageTransitionExit({ delay: Const.EXIT_DELAY })
    9. .opacity(0);
    10. }
    11. }
    12. // IntroductionPage.ets
    13. @Entry
    14. @Component
    15. struct IntroductionPage {
    16. pageTransition() {
    17. PageTransitionEnter({ duration: Const.SHARED_DURATION })
    18. .slide(SlideEffect.Bottom)
    19. .scale({
    20.         x: 0,
    21.         y: 0,
    22.         z: 0,
    23.         centerX: Const.HALF_PERCENT,
    24.         centerY: Const.HALF_PERCENT
    25. });
    26. PageTransitionExit({ delay: Const.SWIPER_DURATION })
    27. .slide(SlideEffect.Bottom)
    28. .scale({
    29.         x: 0,
    30.         y: 0,
    31.         z: 0,
    32.         centerX: Const.HALF_PERCENT,
    33.         centerY: Const.HALF_PERCENT
    34. });
    35. }
    36. }

    6.2 区域详情页

    区域详情页包括首图轮播、滑动缩放、标题吸顶以及图片查看等功能,效果如图所示:

    首先通过imageHeight属性设置轮播的启用与禁用,imageHeight为全屏时轮播启用,左右滑动可以查看不同区域的介绍信息,当imageHeight小于全屏时轮播禁用。

    1. // SwiperListItem.ets
    2. @Component
    3. export default struct SwiperListItem {
    4.   @Prop imageHeightnumber;
    5.   ...
    6.   build() {
    7.     Stack({ alignContentAlignment.Bottom }) {
    8.       Swiper(this.swiperController) {
    9.         ...
    10.       }
    11.       ...
    12.       .indicator(this.imageHeight < CommonConstants.FULL_PERCENT_NUMBER ? false : new DotIndicator())
    13.       .disableSwipe(this.imageHeight < CommonConstants.FULL_PERCENT_NUMBER ? true : false)
    14.     }
    15.   }
    16. }

    接着根据List触屏滑动的偏移量,计算滑动缩放的比例。onScrollFrameBegin方法接收offset参数,返回List的实际偏移量。其中offset大于0为向上滑动,图片缩小;小于0为向下滑动,图片放大。

    1. // IntroductionPage.ets
    2. importAnimation } from '../common/utils/Animation';
    3. ...
    4. @Entry
    5. @Component
    6. struct IntroductionPage {
    7. @State listPositionnumber = Const.LIST_POSITION_BEGIN;
    8. @State imageHeightnumber = Const.FULL_PERCENT_NUMBER;
    9. @State arrowIconOpacitynumber = Const.OPACITY_MAX;
    10. ...
    11. build() {
    12. Column() {
    13. Stack({ alignContentAlignment.Bottom }) {
    14. Column() {
    15. List({ scroller: this.scrollerForList }) {
    16. ...
    17. }
    18. .onScrollFrameBegin((offset: number, state: ScrollState) => {
    19.             let realOffset = Animation.controlImageScale.call(this, offset, state);
    20. returnoffsetRemain: realOffset };
    21. })
    22. ...
    23. }
    24. }
    25. }
    26. }
    27. }

    在滑动缩放过程中,为避免首图滑出屏幕顶端,需要设置List实际偏移量为0。并且基于offset值实时更新imageHeight与arrowIconOpacity实现缩放。

    1. // Animation.ets
    2. import { Const} from '../constants/CommonConstants';
    3. export class Animation {
    4. public static controlImageScale(this, offset: number, state: ScrollState): number {
    5. if ((offset > 0) && (this.imageHeight > CommonConstants.MIN_IMAGE_HEIGHT)) {
    6. // 图片缩小逻辑
    7.       let offsetHeight = (Math.abs(offset) * CommonConstants.FULL_PERCENT_NUMBER) / Number(this.screenHeight);
    8.       let heightOffset = this.imageHeight - CommonConstants.MIN_IMAGE_HEIGHT > offsetHeight ?
    9.         offsetHeight : this.imageHeight - CommonConstants.MIN_IMAGE_HEIGHT;
    10. this.imageHeight = this.imageHeight - heightOffset;
    11. this.arrowIconOpacity = this.arrowIconOpacity -
    12.         heightOffset / (CommonConstants.FULL_PERCENT_NUMBER - CommonConstants.MIN_IMAGE_HEIGHT);
    13. // 返回实际偏移量0
    14. return 0;
    15. }
    16. if ((this.listPosition === CommonConstants.LIST_POSITION_BEGIN) && (offset < 0)
    17. && (this.imageHeight < CommonConstants.FULL_PERCENT_NUMBER)) {
    18. // 图片放大逻辑
    19.       let offsetHeight = (Math.abs(offset) * CommonConstants.FULL_PERCENT_NUMBER) / Number(this.screenHeight);
    20.       let heightOffset = CommonConstants.FULL_PERCENT_NUMBER - this.imageHeight > offsetHeight ?
    21.         offsetHeight : CommonConstants.FULL_PERCENT_NUMBER - this.imageHeight;
    22. this.imageHeight = this.imageHeight + heightOffset;
    23. this.arrowIconOpacity = this.arrowIconOpacity +
    24.         heightOffset / (CommonConstants.FULL_PERCENT_NUMBER - CommonConstants.MIN_IMAGE_HEIGHT);
    25. // 返回实际偏移量0
    26. return 0;
    27. }
    28. ...
    29. // 返回传参offset,此时缩放过程完毕
    30. return offset;
    31. }
    32. }

    介绍信息包括风格、建筑以及地理位置三部分,其中标题部分吸顶,并且需要根据滑动偏移量更新图标。通过scaleIcon数组设置不同标题图标的缩放比,在changeTitleIcon方法中基于偏移量改变scaleIcon数组的值。

    1. // IntroductionPage.ets
    2. importAnimation } from '../common/utils/Animation';
    3. ...
    4. @Entry
    5. @Component
    6. struct IntroductionPage {
    7. @State scaleIconArray<number> = [Const.OPACITY_MAXConst.OPACITY_MIN,
    8.     Const.OPACITY_MIN];
    9. ...
    10. @Builder StickyHeader() {
    11. Column() {
    12. ...
    13. }
    14. }
    15. @Builder StickyFooter() {
    16. Column()
    17. .height($r('app.float.introduction_page_padding_bottom'))
    18. }
    19. }
    20. build() {
    21. Column() {
    22. Stack({ alignContentAlignment.Bottom }) {
    23. Column() {
    24. List({ scroller: this.scrollerForList }) {
    25. ...
    26. }
    27. .onScroll(() => {
    28. this.startAnimation();
    29. })
    30. }
    31. }
    32. }
    33. }
    34. // 标题图标动画部分
    35. startAnimation() {
    36.     Animation.changeTitleIcon.apply(this);
    37. }
    38. ...
    39. }

    计算offsetSum整体偏移量,当滑动到相应介绍模块时改变iconTitle与scaleIcon。

    1. // Animation.ets
    2. import { CommonConstants as Const} from '../constants/CommonConstants';
    3. export class Animation {
    4. public static changeTitleIcon(this) {
    5. this.offsetSum = this.scrollerForList.currentOffset().yOffset;
    6. ...
    7. // 滑动设置listPosition标注当前所在listitem的索引
    8. if (this.offsetSum > Const.OFFSET_SUM_THRESHOLD) {
    9. this.listPosition = Const.LIST_POSITION_MIDDLE;
    10. }
    11. if (this.offsetSum > firstStarLine + Const.FIXED_ITEM_HEIGHT / 2) {
    12. this.geographicPicType = Const.GEOGRAPHY_LIGHT;
    13. }
    14. if (this.offsetSum <= firstStarLine + Const.FIXED_ITEM_HEIGHT / 2) {
    15. this.geographicPicType = Const.GEOGRAPHY_DARK;
    16. }
    17. // 基于总偏移量更新scaleIcon与iconTitle属性
    18. if ((this.currentListIndex === 2) && (this.offsetSum <= firstStarLine)) {
    19. this.iconTitle = Const.ICON_SUBTITLE_ARRAY[0];
    20. this.scaleIcon = [Const.OPACITY_MAX, Const.OPACITY_MIN, Const.OPACITY_MIN];
    21. }
    22. if ((this.currentListIndex === 2) && (this.offsetSum > firstStarLine) && (this.offsetSum < secondStarLine)) {
    23. this.iconTitle = Const.ICON_SUBTITLE_ARRAY[1];
    24. this.scaleIcon = [Const.OPACITY_MIN, Const.OPACITY_MAX, Const.OPACITY_MIN];
    25. }
    26. if ((this.currentListIndex === 2) && (this.offsetSum >= secondStarLine) && (this.offsetSum < thirdStarLine)) {
    27. this.iconTitle = Const.ICON_SUBTITLE_ARRAY[2];
    28. this.scaleIcon = [Const.OPACITY_MIN, Const.OPACITY_MIN, CommonConstants.OPACITY_MAX];
    29. }
    30. }
    31. ...
    32. }

    6.3 查看大图

    在区域详情页的“设计风格”部分,提供了一个可以左右滑动查看的图库,展示了该区域的建筑风貌。点击当前展示的图片,将打开可以查看大图的弹窗,可以左右滑动查看对应图片的高清大图,支持双指缩放和拖动。

    ImageAnimate自定义组件提供了左右滑动查看的图库功能,为了实现查看大图的弹窗,在此组件内添加自定义弹窗控制器,并通过点击事件打开弹窗。

    1. // ImageAnimate.ets
    2. // 导入自定义弹窗组件
    3. import { ImageView } from '../view/ImageViewComponent';
    4. @Component
    5. export default struct ImageAnimation {
    6.   // 添加自定义弹窗控制器
    7.   dialogControllerCustomDialogController = new CustomDialogController({ 
    8.     builderImageView({ currentImageIdthis.currentIndex }),
    9.     customStyletrue,
    10.     alignmentDialogAlignment.Bottom,
    11.   });
    12.   build(){
    13.     Stack() {
    14.       ForEach(this.introductionData.imageList(item: ResourceStr, index: number) => {
    15.         Row() {
    16.           ...
    17.         }
    18.         .onClick(() => {
    19.           // 打开弹窗
    20.           this.dialogController.open();
    21.         })
    22.       }, item => JSON.stringify(item))
    23.     }
    24.   }
    25. }

    在自定义弹窗中,使用Swiper组件实现滑动查看大图的功能,使用Image组件通过控制组件大小实现缩放功能。两者作为Stack的子组件,通过手势识别判断当前是滑动查看不同大图的操作还是图片缩放和拖动的操作,控制对应组件的显隐,来实现对应功能。

    1. // ImageViewComponent.ets
    2. @CustomDialog
    3. export struct ImageView {
    4. build() {
    5. Stack(){
    6. Swiper() {
    7. ForEach(this.introductionData.imageList, (item: Resource) => {
    8. Column() {
    9. Blank()
    10. .onClick(() => {
    11. // 使用Blank组件填充空白处,点击可以关闭弹窗
    12. this.controller.close();
    13. })
    14. Image(item)
    15. .gesture(
    16. // 触发捏合手势
    17. PinchGesture()
    18. .onActionStart(() => {
    19. // 识别到手势操作,将isGesture设为true
    20. this.isGesture = true;
    21. })
    22. .onActionUpdate((event: GestureEvent) => {
    23. // 随着捏合操作的过程,逐渐调整图片缩放倍数
    24. this.imgScale = this.curScale * event.scale;
    25. })
    26. .onActionEnd(() => {
    27. // 为了避免图片无限缩放,在捏合操作结束时控制缩放倍数的值
    28. this.limitScale(false);
    29. })
    30. )
    31. // 根据isGesture的值来控制显隐
    32. .visibility(this.isGesture ? Visibility.Hidden : Visibility.Visible)
    33. Blank()
    34. .onClick(() => {
    35. this.controller.close();
    36. })
    37. }
    38. ...
    39. }, item => JSON.stringfy(item))
    40. }
    41. ...
    42. .onChange((indexnumber) => {
    43. // swiper滑动时记录切换的index
    44. this.curIndex = index;
    45. })
    46. Row() {
    47. // 根据切换的index显示对应的图片
    48. Image(this.introductionData.imageList[this.curIndex])
    49. .objectFit(ImageFit.Contain)
    50. // 控制图片缩放倍数
    51. .scale({ x: this.imgScale, y: this.imgScale })
    52. // 控制图片偏移值
    53. .translate({ x: this.imgOffsetX, y: this.imgOffsetY })
    54. .onComplete((event) => {
    55. this.imgWidth = event.width;
    56. this.imgHeight = event.height;
    57. // 根据图片宽高计算图片不缩放时的实际高度
    58. this.displayHeight = this.deviceWidth * this.imgHeight / this.imgWidth;
    59. })
    60. }
    61. .gesture(
    62. // 触发捏合手势
    63. PinchGesture()
    64. .onActionUpdate((event: GestureEvent) => {
    65. // 随着捏合操作的过程,逐渐调整图片缩放倍数
    66. this.imgScale = this.curScale * event.scale;
    67. })
    68. .onActionEnd(() => {
    69. // 为了避免图片偏移超出屏幕边界,检测到偏移值到达最大时停止继续偏移
    70. this.detectBoundary();
    71. // 为了避免图片无限缩放,在捏合操作结束时控制缩放倍数的值,并重置偏移值
    72. this.limitScale(true);
    73. })
    74. )
    75. .gesture(
    76. // 触发拖动手势
    77. PanGesture()
    78. .onActionStart(() => {
    79. // 记录先前的偏移值
    80. this.preOffsetX = this.imgOffsetX;
    81. this.preOffsetY = this.imgOffsetY;
    82. })
    83. .onActionUpdate((event: GestureEvent) => {
    84. // 随着拖动操作的过程,不断改变图片偏移值
    85. this.imgOffsetX = this.preOffsetX + event.offsetX;
    86. this.imgOffsetY = this.preOffsetY + event.offsetY;
    87. })
    88. .onActionEnd(() => {
    89. // 为了避免图片偏移超出屏幕边界,检测到偏移值到达最大时停止继续偏移
    90. this.detectBoundary();
    91. })
    92. )
    93. // 根据isGesture的值来控制显隐
    94. .visibility(this.isGesture ? Visibility.Visible : Visibility.Hidden)
    95. }
    96. ...
    97. }
    98. }

    七、小火车

    小火车模块提供了溪村小镇小火车的相关信息,主要功能如下:

    1. 查看溪村小火车三条路线的概览图。
    2. 点击对应路线展示当前时间每条路线上小火车运营状态、时刻表、所在的位置、运动方向、及实时运动轨迹。效果如图所示:

    注意:非运营时间内,不展示路线图。

    7.1 页面布局

    主页面以Navigation组件作为根组件,可直接设置标题,上方Image组件展示小火车的路线概览图,下方List组件循环展示三条路线的信息及火车轨迹动图。

    1. // TrainsComponent.ets
    2. build() {
    3. Navigation() {
    4. Column({ space: Const.TRAIN_SPACE }) {
    5. Image($r('app.media.ic_train_map'))
    6. .aspectRatio(Const.TRAIN_ASPECT_RATIO)
    7. .objectFit(ImageFit.Cover)
    8. .borderRadius(Const.TRAIN_BORDER_RADIUS)
    9. List({ space: Const.TRAIN_SPACE }) {
    10. ForEach(this.trainsMapData, (item: TrainsMap, indexnumber) => {
    11. ListItem() {
    12. Column({ space: Const.TRAIN_SPACE }) {
    13.       ...
    14. if (this.fetchShowMap(index)) {
    15. // 小火车运行轨迹组件
    16. TrainsTrack({ trainsInfo: this.trainsMapData[index], trainLine: index })
    17. }
    18. }
    19. ...
    20. }
    21. }, item => JSON.stringify(item))
    22. }
    23. .layoutWeight(1)
    24. .edgeEffect(EdgeEffect.None)
    25. }
    26. .padding({ left: Const.TRAIN_PADDING_LEFTright: Const.TRAIN_PADDING_RIGHT })
    27. .height(Const.FULL_SIZE)
    28. .backgroundColor($r("app.color.train_background"))
    29. }
    30. .title(Const.TRAIN_TITLE)
    31. .titleMode(NavigationTitleMode.Full)
    32. .hideToolBar(true)
    33. .hideBackButton(true)
    34. .backgroundColor($r("app.color.train_background"))
    35. }

    火车轨迹更新页面封装在子组件TrainsTrack.ets中,以Stack组件为根组件,地图背景使用Canvas组件绘制,小火车的箭头使用Image组件定位绘制,小火车图标的其他地方均使用第二个Canvas组件绘制。

    1. // TrainsTrack.ets
    2. build() {
    3. Stack() {
    4. // 小火车运行背景轨迹
    5. Canvas(this.context)
    6. .width(Const.FULL_SIZE)
    7. .aspectRatio(Const.CANVAS_ASPECT_RADIO)
    8. .borderRadius(Const.CANVAS_BORDER_RADIUS)
    9. .onReady(() => {
    10. ...
    11. })
    12. Image(Const.ARROW_URL)
    13. .width(Const.ARROW_WIDTH)
    14. .height(Const.ARROW_HEIGHT)
    15. .position({
    16.         x: this.trainX + this.bgX - Const.ARROW_OFFSET_X,
    17.         y: this.trainY + this.bgY - Const.ARROW_OFFSET_Y
    18. })
    19. .rotate({
    20.         x: 0,
    21.         y: 0,
    22.         z: 1,
    23.         angle: this.rotateAngle
    24. })
    25. // 小火车导航图
    26. Canvas(this.contextTrainLine)
    27. .width(Const.FULL_SIZE)
    28. .aspectRatio(Const.CANVAS_ASPECT_RADIO)
    29. .borderRadius(Const.CANVAS_BORDER_RADIUS)
    30. .onReady(() => {
    31. ...
    32. })
    33. }
    34. }

    7.2 初始化小火车信息

    点击对应路线的小火车,会显示或隐藏小火车的运动轨迹,当首次显示小火车的运动轨迹时,需要初始化一些信息,包括小火车当前时间运动的位置、背景区域的位置、小火车的轨迹更新时间等。

    在子组件的aboutToAppear中,调用自定义的初始化方法calcDistance,方法接收一个参数即小火车的运动坐标点数组,根据路线参数不同可以获取不同路线小火车运动一周的总路程。

    1. // TrainsTrack.ets
    2. aboutToAppear() {
    3. this.sumDistance = TrainsMapModel.calcDistance(this.trainsInfo.lineData);
    4. ...
    5. }
    6. // TrainsMapModel.ets
    7. calcDistance(data: Position[]): number {
    8.   let sumDistance: number = 0;
    9. const length = data.length;
    10.   data.forEach((item: Position, indexnumber) => {
    11. const startX = item.x;
    12. const startY = item.y;
    13. const endX = index === length - 1data[0].x : data[index + 1].x;
    14. const endY = index === length - 1data[0].y : data[index + 1].y;
    15. if (Math.abs(startX - endX) >= Math.abs(startY - endY)) {
    16.       sumDistance += Math.abs(startX - endX);
    17. } else {
    18.       sumDistance += Math.abs(startY - endY);
    19. }
    20. })
    21. return sumDistance;
    22. }

    获取总路程后,通过获取当前的时间、小火车的出发时间、以及始发站坐标,计算小火车在当前时间从始发站开始走过的距离。

    1. // TrainsMapModel.ets
    2. travelDistance(distance: number, startTime: stringlinenumber): number {
    3.   let ret: number = 0;
    4. const date = new Date();
    5. const dateStr = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} `;
    6. const startDate = new Date(dateStr + startTime).getTime();
    7. const currentDate = date.getTime();
    8. const diff = currentDate - startDate;
    9. switch (line) {
    10. case TrainsLine.LINE_ONE:
    11.       ret = distance * (diff % (Const.LINE_ONE_TIME)) / (Const.LINE_ONE_TIME);
    12. break;
    13. case TrainsLine.LINE_TWO:
    14.       ret = distance * (diff % (Const.LINE_TWO_TIME)) / (Const.LINE_TWO_TIME);
    15. break;
    16. case TrainsLine.LINE_THREE:
    17.       ret = distance * (diff % (Const.LINE_THREE_TIME)) / (Const.LINE_THREE_TIME);
    18. break;
    19. default:
    20.       ret = 0;
    21. }
    22. return Number(ret.toFixed(2));
    23. }

    在上一个方法中获取到小火车从始发站走过的距离,再通过路线坐标点可以得到当前小火车在路线图上的最近坐标位置。

    1. // TrainsTrack.ets
    2. calcFirstDistance(data: Position[], travelDistance: number) {
    3.   let sumDistance: number = 0;
    4.   const length = data.length;
    5.   for (let index = 0;index < lengthindex++) {
    6.     if (sumDistance > travelDistance) {
    7.       this.currentIndex = index - 1;
    8.       this.trainX = data[index - 1].x;
    9.       this.trainY = data[index - 1].y;
    10.       this.calcPosition(this.trainX, this.trainY, this.canvasWidth, this.canvasHeight);
    11.       break;
    12.     } else {
    13.       const startX = data[index].x, startY = data[index].y;
    14.       const endX = index === length - 1 ? data[0].x : data[index+1].x,
    15.         endY = index === length - 1 ? data[0].y : data[index+1].y;
    16.       if (Math.abs(startX - endX) >= Math.abs(startY - endY)) {
    17.         sumDistance += Math.abs(startX - endX);
    18.       } else {
    19.         sumDistance += Math.abs(startY - endY);
    20.       }
    21.     }
    22.   }
    23. }

    小火车的路线与运行一圈的时间均不相同,但是每次更新位置的距离都是1vp,所以需要计算每条路线小火车更新轨迹的时间间隔,这里计算时间间隔通过总距离/运行一圈时间获得。

    1. // TrainsMapModel.ets
    2. calcDelay(distance: numberlinenumber): number {
    3.   let ret: number = 0;
    4. switch (line) {
    5. case TrainsLine.LINE_ONE:
    6.       ret = Const.LINE_ONE_TIME / distance;
    7. break;
    8. case TrainsLine.LINE_TWO:
    9.       ret = Const.LINE_TWO_TIME / distance;
    10. break;
    11. case TrainsLine.LINE_THREE:
    12.       ret = Const.LINE_THREE_TIME / distance;
    13. break;
    14. default:
    15.       ret = 0;
    16. }
    17. return ret;
    18. }

    7.3 更新小火车轨迹

    根据初始化计算的更新时间及下次小火车即将到达的地点,更新小火车的位置,同时计算更新底层地图的显示位置。

    通过setInterval函数,每隔一段时间重新清除画布上的小火车,并重新绘制小火车,包括位置、方向等。

    1. // TrainsTrack.ets
    2. drawTrainPosition() {
    3. if (Math.abs(this.trainX - this.positionEnd.x) <= Const.AVERAGE_ERROR &&
    4.   Math.abs(this.trainY - this.positionEnd.y) <= Const.AVERAGE_ERROR) {
    5. this.trainX = this.positionEnd.x;
    6. this.trainY = this.positionEnd.y;
    7. if (this.currentIndex === this.trainsInfo.lineData.length - 2) {
    8. this.currentIndex = 0;
    9. } else {
    10. this.currentIndex += 1;
    11. }
    12. }
    13. this.positionStart = this.trainsInfo.lineData[this.currentIndex];
    14. this.positionEnd = this.trainsInfo.lineData[this.currentIndex + 1];
    15. this.rotateAngle = Const.BASIC_ROTATE_ANGLE + TrainsMapModel.fetchDirection(this.positionStart.x, this.positionStart.y, this.positionEnd.x, this.positionEnd.y);
    16. this.contextTrainLine.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
    17. this.trainX += TrainsMapModel.fetchRatioX(this.positionStart, this.positionEnd);
    18. this.trainY += TrainsMapModel.fetchRatioY(this.positionStart, this.positionEnd);
    19. this.calcPosition(this.trainX, this.trainY, this.canvasWidth, this.canvasHeight);
    20. this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
    21. this.context.drawImage(this.trainsInfo.imgBg, this.bgX, this.bgY, Const.CANVAS_WIDTH, Const.CANVAS_HEIGHT);
    22. this.contextTrainLine.drawImage(
    23. this.imgTrain,
    24. this.trainX + this.bgX - Const.TRAIN_OFFSET_X,
    25. this.trainY + this.bgY - Const.TRAIN_OFFSET_Y,
    26.     Const.TRAIN_WIDTH,
    27.     Const.TRAIN_HEIGHT
    28. );
    29. this.contextTrainLine.drawImage(
    30. this.imgCircle,
    31. this.trainX + this.bgX - Const.CIRCLE_OFFSET_X,
    32. this.trainY + this.bgY - Const.CIRCLE_OFFSET_Y,
    33.     Const.CIRCLE_WIDTH,
    34.     Const.CIRCLE_HEIGHT
    35. );
    36. }
    37. build() {
    38. Stack() {
    39. ...
    40. Canvas(this.contextTrainLine)
    41. .width(Const.FULL_SIZE)
    42. .aspectRatio(Const.CANVAS_ASPECT_RADIO)
    43. .borderRadius(Const.CANVAS_BORDER_RADIUS)
    44. .onReady(() => {
    45. ...
    46. setInterval(() => {
    47. this.drawTrainPosition();
    48. }, this.delay)
    49. })
    50. }
    51. }

    每次需要计算小火车横向和竖向运动的距离,这里我们以每次运动1vp为单位,如果当前坐标相对于下次坐标,横向运动距离更长,为了保持匀速,那么竖向运动距离需要计算一个运动比例,反之一样。

    1. // TrainsMapModel.ets
    2. fetchRatioX(start: Position, end: Position): number {
    3.   let diffX = start.x - end.x;
    4.   let diffY = start.y - end.y;
    5. if (Math.abs(diffX) >= Math.abs(diffY)) {
    6. return -diffX / Math.abs(diffX);
    7. } else {
    8. return -Number((diffX / Math.abs(diffY)).toFixed(2));
    9. }
    10. }
    11. fetchRatioY(start: Position, end: Position): number {
    12.   let diffX = start.x - end.x;
    13.   let diffY = start.y - end.y;
    14. if (Math.abs(diffY) >= Math.abs(diffX)) {
    15. return -diffY / Math.abs(diffY);
    16. } else {
    17. return -Number((diffY / Math.abs(diffX)).toFixed(2));
    18. }
    19. }

    小火车图标包含方向箭头,默认是指向上方,当小火车每次运动的时候,需要更新小火车的箭头方向,通过计算开始坐标与结束坐标的比例,计算旋转角度。

    1. // TrainsMapModel.ets
    2. fetchDirection(startX: number, startY: number, endX: number, endY: number): number {
    3.   let ret;
    4. if (startX === endX) {
    5. return startY > endY ? 0 : Const.DIRECTION * 2;
    6. }
    7. if (startY === endY) {
    8. return startX > endX ? -Const.DIRECTION : Const.DIRECTION;
    9. }
    10.   let angle = this.calcAngle(startX, startY, endX, endY);
    11. if (startX > endX && startY > endY) {
    12.     ret = -(Const.DIRECTION - angle);
    13. }
    14. if (startX > endX && startY < endY) {
    15.     ret = -Const.DIRECTION - angle;
    16. }
    17. if (startX < endX && startY > endY) {
    18.     ret = Const.DIRECTION - angle;
    19. }
    20. if (startX < endX && startY < endY) {
    21.     ret = Const.DIRECTION + angle;
    22. }
    23. return ret;
    24. }
    25. calcAngle(startX: number, startY: number, endX: number, endY: number): number {
    26. const x = Math.abs(startX - endX);
    27. const y = Math.abs(startY - endY);
    28. const radianA = Math.atan(y / x);
    29. const angleA = Math.round(Const.PI_ANGLE / Math.PI * radianA);
    30. return angleA;
    31. }

    因为小火车是实时运动的,下方的轨迹地图比展示区域要大很多,所以当小火车即将运动出显示范围的时候,需要实时更新下方地图的位置,保证小火车一直在展示区域的轨迹上运动。

    1. // TrainsTrack.ets
    2. calcPosition(x, y, w, h) {
    3. if (x + this.bgX > w - Const.HORIZONTAL_THRESHOLD) {
    4. this.bgX = Math.abs(this.bgX - w / 2> Const.CANVAS_WIDTH - w ? -Const.CANVAS_WIDTH + w : this.bgX - w / 2;
    5. }
    6. if (x + this.bgX < Const.HORIZONTAL_THRESHOLD) {
    7. this.bgX = Math.abs(this.bgX + w / 2< 0 ? 0 : this.bgX + w / 2;
    8. }
    9. if (y + this.bgY > h - Const.VERTICAL_THRESHOLD) {
    10. this.bgY = Math.abs(this.bgY - h / 2> Const.CANVAS_HEIGHT - h ? -Const.CANVAS_HEIGHT + h : this.bgY - h / 2;
    11. }
    12. if (y + this.bgY < Const.VERTICAL_THRESHOLD) {
    13. this.bgY = Math.abs(this.bgY + h / 2< 0 ? 0 : this.bgY + h / 2;
    14. }
    15. }

    八、总结

    您已经完成了本次Codelab的学习,并了解到以下知识点:

    1. 实现页面跳转和自定义弹窗。
    2. 识别用户操作手势并触发相应事件。
    3. 添加页面动画效果。
    4. 使用画布组件自定义绘制图形。
  • 相关阅读:
    关于ElasticSearch版本7.8.0进行排坑
    Akshare获取分红数据
    c++类型转换static_cast dynamic_cast const_cast reinterpret_cast
    解决Tomcat闪退问题
    Kubernetes 进阶训练营 控制器
    如何将计算机上有限的物理内存分配给多个程序使用
    OneFlow v0.6.0正式发布
    Redis Part1
    【仿牛客网笔记】Spring Boot实践,开发社区登录模块-显示登录信息
    基于哈尔小波基的一维密度估计(Python)
  • 原文地址:https://blog.csdn.net/HarmonyOSDev/article/details/132847629