HarmonyOS 鸿蒙Next L-Weather开发经验分享(Codelabs挑战赛第二期)
L-Weather介绍
简介
本应用是投稿于HarmonyOS跳转赛第二期作品一个真实可用的天气应用,可通过axios获取实时天气信息(天气、温度、湿度、风向和更新时间)并加载显示主页上,并根据天气情况加载不同Lottie天气动画效果。
应用效果
海南-云
广东-晴
浙江-小雨
黑龙江-雪
海南-雷阵雨
三方库关键代码
本地Axios
"dependencies": {
"@ohos/axios": "file:../ohos_axios"
}
调用网络请求三方库 Axios 获取天气数据
import { axios } from '@ohos/axios'
axios({
method: "get",
url: 'https://restapi.amap.com/v3/weather/weatherInfo?city=460300&key=08e8926bcbccb652db60765098424501'
}).then(res => {
let response: WeatherInfo = res.data;
LogUtil.info(TAG, 'response:' + JSON.stringify(response));
// 信息赋值
let liveWeather = response.lives[0];
this.liveWeather = liveWeather.weather;
this.location = liveWeather.province + ' ' + liveWeather.city;
this.temperature = liveWeather.temperature + '°C';
this.reportTime = '更新时间:' + liveWeather.reporttime;
let humidity = liveWeather.humidity + '%';
let windDirection = liveWeather.winddirection + '风';
this.listData = [
{ image: $r('app.media.humidity'), text: humidity },
{ image: $r("app.media.wind"), text: windDirection },
]
}).catch(error => {
LogUtil.error(TAG, 'initWeatherInfo error' + JSON.stringify(error));
})
社区lottieETS
下载安装
npm config set @ohos:registry=https://repo.harmonyos.com/npm/npm install @ohos/lottieETS --save
调用动画库 lottieETS 加载不同的天气效果,并将其封装到自定义组件WeatherAnimation.ets中
import lottie from '@ohos/lottieETS'
@Componentstruct
class WeatherAnimation {
@Prop @Watch('updateWeather')
liveWeather: string;
private mainRenderingSettings: RenderingContextSettings = new RenderingContextSettings(true)
private mainCanvasRenderingContext: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.mainRenderingSettings)
private path: string = '/common/lottie/mist.json'
build() {
Column() {
Canvas(this.mainCanvasRenderingContext)
.width('100%')
.height(200)
}
.width('100%')
}
initLottie() {
if(this.liveWeather.includes('雷')){
this.path = '/common/lottie/thunder.json'
} else if(this.liveWeather.includes('云') || this.liveWeather.includes('风')){
this.path = '/common/lottie/mist.json'
} else if(this.liveWeather.includes('雨')){
this.path = '/common/lottie/shower.json'
} else if(this.liveWeather.includes('雪')){
this.path = '/common/lottie/snow.json'
} else {
this.path = '/common/lottie/sunny.json'
}
LogUtil.info(TAG,'this.liveWeather = ' + this.liveWeather)
LogUtil.info(TAG,'this.path = ' + this.path)
let animationItem = lottie.loadAnimation({
container: this.mainCanvasRenderingContext,
renderer: 'canvas',
loop: true,
autoplay: true,
path: this.path,
})
animationItem.play()
}
updateWeather(){
LogUtil.info(TAG,'updateWeather')
this.initLottie()
}
}
export default WeatherAnimation
安装部署
- 下载DevEco Studio
- 使用模拟器运行应用/服务 [参考链接]
更多关于HarmonyOS 鸿蒙Next L-Weather开发经验分享(Codelabs挑战赛第二期)的实战教程也可以访问 https://www.itying.com/category-93-b0.html
1 回复