鸿蒙Harmony OS Next原生开发天气预报项目天气信息页面渲染

鸿蒙初开,开天辟地

鸿蒙Harmony OS Next原生开发天气预报项目天气信息页面渲染 

import { cityView } from '../view/cityView';
import getWeatherUtil from "../viewmodel/getWeatherUtil";
import { weatherModel } from '../viewmodel/weatherModel';

@Entry
@Component
struct Index {
  // 城市代码集合
  @State cityCodeList:number[] = [440300,440100];
  // 城市名字集合
  @State cityNameList:string[] = [];
  // 城市信息集合
  @State cityWeatherList:Array = [];
  // 当前城市索引
  @State cityIndex:number = 0;
  tabController:TabsController = new TabsController();
  // 按钮样式
  @Builder tabBuild(index:number){
    Circle({width:10,height:10}).fill(this.cityIndex === index?Color.White:Color.Gray).opacity(0.4);
  }
  // 获取数据
  aboutToAppear(): void {
    this.initDate();
  }
  // 初始化方法
  async initDate(){
    let result:Array = await getWeatherUtil.getWeathers(this.cityCodeList);
    for (let i = 0; i < result.length i let weather:weathermodel='result[i];' this.cityweatherlist.pushweather this.citynamelist.pushweather.forecasts0.city build column row button.fontsize25.fontcolorcolor.gray.opacity0.7.backgroundcolor87ceeb.marginbottom:15 textthis.citynamelistthis.cityindex.fontsize40.fontcolorcolor.orange button.fontsize25.fontcolorcolor.gray.opacity0.7.backgroundcolor87ceeb.marginbottom:15 .width100.height10.justifycontentflexalign.spacebetween tabsbarposition:barposition.startcontroller:this.tabcontroller>{
          TabContent(){
            cityView({casts:cityWeather.forecasts[0].casts});
          }.tabBar(this.tabBuild(this.cityWeatherList.findIndex(obj=>obj===cityWeather)));
        });
      }.barWidth(20).barHeight(40).onChange((index:number)=>{
        this.cityIndex = index;
      });
    }.width("100%").height("100%").backgroundColor("#87CEEB");
  }
}

import { cityView } from '../view/cityView';
import getWeatherUtil from "../viewmodel/getWeatherUtil";
import { weatherModel } from '../viewmodel/weatherModel';

@Entry
@Component
struct Index {
  // 城市代码集合
  @State cityCodeList:number[] = [440300,440100];
  // 城市名字集合
  @State cityNameList:string[] = [];
  // 城市信息集合
  @State cityWeatherList:Array = [];
  // 当前城市索引
  @State cityIndex:number = 0;
  tabController:TabsController = new TabsController();
  // 按钮样式
  @Builder tabBuild(index:number){
    Circle({width:10,height:10}).fill(this.cityIndex === index?Color.White:Color.Gray).opacity(0.4);
  }
  // 获取数据
  aboutToAppear(): void {
    this.initDate();
  }
  // 初始化方法
  async initDate(){
    let result:Array = await getWeatherUtil.getWeathers(this.cityCodeList);
    for (let i = 0; i < result.length i let weather:weathermodel='result[i];' this.cityweatherlist.pushweather this.citynamelist.pushweather.forecasts0.city build column row button.fontsize25.fontcolorcolor.gray.opacity0.7.backgroundcolor87ceeb.marginbottom:15 textthis.citynamelistthis.cityindex.fontsize40.fontcolorcolor.orange button.fontsize25.fontcolorcolor.gray.opacity0.7.backgroundcolor87ceeb.marginbottom:15 .width100.height10.justifycontentflexalign.spacebetween tabsbarposition:barposition.startcontroller:this.tabcontroller>{
          TabContent(){
            cityView({casts:cityWeather.forecasts[0].casts});
          }.tabBar(this.tabBuild(this.cityWeatherList.findIndex(obj=>obj===cityWeather)));
        });
      }.barWidth(20).barHeight(40).onChange((index:number)=>{
        this.cityIndex = index;
      });
    }.width("100%").height("100%").backgroundColor("#87CEEB");
  }
}

import { cast } from '../viewmodel/cast';

@Component
export struct cityView{
  // 获取数据,城市数据
  casts:Array = [];
  // 展示数据
  build() {
    Column(){
      // 当天天气数据
      ForEach(this.casts,(cast:cast)=>{
        if(this.casts[0] === cast){
          // 图片渲染
          Row(){
            if(cast.dayweather === "晴"){
              Image("https://i-blog.csdnimg.cn/direct/bf01538113ef4f218fd4495c430e0568.jpeg")
                .width(260).height("100%");
            }
            if(cast.dayweather === "阴"){
              Image("https://i-blog.csdnimg.cn/direct/cdccb8075bb8473db2672bed70190ba7.jpeg")
                .width(260).height("100%");
            }
            if(cast.dayweather === "多云"){
              Image("https://i-blog.csdnimg.cn/direct/cc6430c2542b4f49b98d33bac2005829.jpeg")
                .width(260).height("100%");
            }
            if(cast.dayweather.includes("雨")){
              Image("https://i-blog.csdnimg.cn/direct/de1260f193c446e7a1e9468140997ae2.jpeg")
                .width(260).height("100%");
            }
          }.height("50%");
          Column(){
            // 气温,天气
            Text(`${cast.dayweather} ${cast.daytemp}° 至 ${cast.nighttemp}°`).fontSize(30)
              .fontColor(Color.White).fontWeight(FontWeight.Bold);
            Text(`${cast.daywind}风${cast.daypower}级`).fontSize(30)
              .fontColor(Color.White).fontWeight(FontWeight.Bold);
          }.margin({top:20});
          Column(){
            Text(`近期天气查询`).fontSize(26).margin({top:30})
          }.width("100%").height("45%");
        }
      });
    }.width("100%").height("100%");
  }
}

import { cast } from '../viewmodel/cast';

@Component
export struct cityView{
  // 获取数据,城市数据
  casts:Array = [];
  // 展示数据
  build() {
    Column(){
      // 当天天气数据
      ForEach(this.casts,(cast:cast)=>{
        if(this.casts[0] === cast){
          // 图片渲染
          Row(){
            if(cast.dayweather === "晴"){
              Image("https://i-blog.csdnimg.cn/direct/bf01538113ef4f218fd4495c430e0568.jpeg")
                .width(260).height("100%");
            }
            if(cast.dayweather === "阴"){
              Image("https://i-blog.csdnimg.cn/direct/cdccb8075bb8473db2672bed70190ba7.jpeg")
                .width(260).height("100%");
            }
            if(cast.dayweather === "多云"){
              Image("https://i-blog.csdnimg.cn/direct/cc6430c2542b4f49b98d33bac2005829.jpeg")
                .width(260).height("100%");
            }
            if(cast.dayweather.includes("雨")){
              Image("https://i-blog.csdnimg.cn/direct/de1260f193c446e7a1e9468140997ae2.jpeg")
                .width(260).height("100%");
            }
          }.height("50%");
          Column(){
            // 气温,天气
            Text(`${cast.dayweather} ${cast.daytemp}° 至 ${cast.nighttemp}°`).fontSize(30)
              .fontColor(Color.White).fontWeight(FontWeight.Bold);
            Text(`${cast.daywind}风${cast.daypower}级`).fontSize(30)
              .fontColor(Color.White).fontWeight(FontWeight.Bold);
          }.margin({top:20});
          Column(){
            Text(`近期天气查询`).fontSize(26).margin({top:30})
          }.width("100%").height("45%");
        }
      });
    }.width("100%").height("100%");
  }
}

最终效果一览

### 如何在鸿蒙原生开发环境下基于 API13 引入 ECharts 图表 #### 1. 鸿蒙环境支持情况分析 鸿蒙系统提供了多种应用开发模式,包括 Java、JS 和 ArkTS 等。然而,ECharts 是一个专门为 Web 开发设计的 JavaScript 图表库,在传统的鸿蒙 Native 应用中并不直接兼容[^2]。因此,要在鸿蒙原生环境中使用 ECharts,通常需要借助 WebView 或者通过跨平台框架实现。 #### 2. 使用 WebView 加载 ECharts WebView 提供了一种简单的方式将 Web 技术嵌入到本地应用程序中。以下是具体方法: - **创建 WebView 组件** 在 HarmonyOS 的 XML 布局文件中定义 `Web` 组件: ```xml <?xml version="1.0" encoding="utf-8"?> <DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:height="match_parent" ohos:width="match_parent" ohos:orientation="vertical"> <Web ohos:id="$+id:webview" ohos:height="match_parent" ohos:width="match_parent"/> </DirectionalLayout> ``` - **加载 HTML 文件并集成 ECharts** 创建一个包含 ECharts 的 HTML 页面,并将其放置于资源目录下(如 `rawfile`)。HTML 示例如下: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ECharts Example</title> <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script> </head> <body> <div id="main" style="width: 600px; height: 400px;"></div> <script type="text/javascript"> var chartDom = document.getElementById('main'); var myChart = echarts.init(chartDom); var option; option = { title: { text: 'ECharts Demo' }, tooltip: {}, legend: { data:['Sales'] }, xAxis: { data: ['Shirt', 'Cardigan', 'Chiffon Shirt', 'Pants', 'Heels', 'Socks'] }, yAxis: {}, series: [{ name: 'Sales', type: 'bar', data: [5, 20, 36, 10, 10, 20] }] }; myChart.setOption(option); </script> </body> </html> ``` 接下来,在代码逻辑中加载该 HTML 文件: ```javascript import web from '@ohos.web'; export default { onInit() { this.webView = this.$element('webview').getComponent(); const filePath = '/data/local/rawfile/index.html'; // 替换为实际路径 this.webView.loadUrl(filePath); } }; ``` #### 3. 跨平台解决方案 如果希望更灵活地利用现代前端技术栈,则可以考虑采用 UniApp 或 Tauri 这样的跨平台工具来构建项目[^4]。这些框架允许开发者编写一次代码即可运行在多个平台上,从而简化了复杂场景下的适配工作量。 #### 4. 数据动态刷新机制 当涉及到频繁的数据更新操作时,需要注意及时触发界面重绘过程以反映最新变化。例如,在 Vue 中可以通过调用 `$forceUpdate()` 来强制重新渲染整个组件树结构;而在纯 JS 实现里则需手动销毁旧实例再重建新对象完成替换动作[^3]。 --- ### 总结 综上所述,虽然 ECharts 并未针对 HarmonyOS NEXT 特定优化过,但我们依然能够依靠现有手段——无论是内置浏览器控件还是第三方生态体系的支持——成功达成目标需求。不过值得注意的是,随着官方文档持续迭代升级以及社区贡献者的努力推进,未来或许会有更加简便高效的途径可供选择!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值