
本文来源:https://www.hqwc.cn/a/1771455.html
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。
HarmonyOS Next温湿度监测:数据卡片与Canvas环形图实战
做智能家居或环境监测类应用的朋友,应该都躲不开温湿度面板这种页面。这课记录的是我在HarmonyOS Next上实现温湿度监测界面的完整过程,核心围绕两个技术点:数据卡片和环形图。数据卡片主要用ArkUI的声明式布局能力搭建,环形图则基于Canvas组件从零手绘,包括刻度、渐变弧线、中心数值和动画过渡。如果你正在折腾鸿蒙应用开发,尤其是想搞懂Canvas绘图、动画驱动、组件生命周期配合这类问题,这篇内容可以直接照着抄。
先看最终效果:顶部是两个数据卡片,分别展示当前温度和湿度,包含图标、数值、单位以及状态描述;下方是两个环形图,左侧显示温度,右侧显示湿度,环的弧长代表当前值在量程中的占比,弧线末端还有渐变色和圆点装饰。数据通过定时器模拟传感器上报,切换页面或点击卡片时,环形图会重新做一次过渡动画。
在HarmonyOS Next生态里,图表库的选择目前不算丰富,像MPAndroidChart这种老牌库在鸿蒙上要么用法不通用、要么维护不活跃,强制适配的成本可能比直接手写还高。环形图本身结构并不复杂,核心就是一个带缺口和弧线进度的圆环,用Canvas完全控制得过来,还省去引入依赖带来的包体积、兼容性和学习成本。
另一个考量是,鸿蒙的Canvas接口和Web Canvas、Android Canvas都有继承关系,熟悉任何一端的绘制逻辑,迁移过来都不难。后面我会详细列出绘制环形图用到的全部API和数学换算,只要按步骤来,入门门槛很低。
顶层使用 Column 纵向布局,控制整体边距和对齐方式。
中间是2×2的网格区域,用 Row 横向排列两列,分别放数据卡片和环形图。
底层是数据刷新逻辑,用 setInterval 模拟传感器采集,通过 @State 驱动UI更新。
之所以把数据卡片和环形图分开用不同的 @Component 封装,主要是考虑状态变更时的渲染范围控制。温度数值每秒变化一次,如果整个页面都参与重新渲染,虽然HarmonyOS的Diff算法能拦截掉没有变化的部分,但把刷新粒度缩小到子组件内,代码上维护起来更清晰,也方便以后单独复用温度卡片或湿度环形图。
看到热搜词里有"Android Studio 实现自定义View环形图,提供一个完整的Java示例代码",说明不少人有跨端对比的需求。简单说一下区别:
Android自定义View需要继承 View ,重写 onMeasure 、 onDraw ,用 Paint + Canvas 画图,涉及自定义属性、 MeasureSpec 等一堆配套知识。HarmonyOS Next的ArkUI则把UI描述移到了 build 里,通过 Canvas(this.context) 声明画布,在 onReady 回调里拿到 CanvasRenderingContext2D 对象,绘制逻辑几乎和Android的Canvas API一致—— beginPath() 、 arc() 、 stroke() 、 fill() 这些方法名都一样。
所以如果你以前写过Android环形图,切到鸿蒙这边的学习曲线相当平缓。差别主要体现在:鸿蒙用 RenderingContextSettings 控制抗锯齿,绘制时使用的长度单位需要做 vp 到 px 的换算,以及动画驱动不能靠 invalidate() ,得用 Canvas 自带的动画帧接口。这些在后面的代码里都会有对应处理。
2. 数据卡片搭建:监测面板的核心布局
数据卡片这里,我参考了鸿蒙官方示例中经常用到的圆角卡片方案,没有选择过于复杂的描边或者多层阴影。卡片基础样式如下:
背景色: '#FFFFFF' ,纯白底保证和页面浅灰背景区分开来。
圆角: 16vp ,配合 shadow 属性拉出一个很轻的阴影,避免整个页面看起来太"平"。
内边距:左右 16vp 、上下 14vp ,保证内容不贴边,手感和视觉都比较舒服。
结构上分成左右两半:左侧放图标和标签文字,右侧放数值和单位。数值用大号字体突出显示,单位用小号灰色字体放在数值右上方或者紧挨着数值。
这里有个细节:温度卡片和湿度卡片的图标、主色都不同。我用了 Flex 布局让图标和文字垂直居中对齐,减少手动margin调位置的麻烦。鸿蒙的 Flex 组件的 justifyContent 、 alignItems 和CSS Flexbox几乎一致,理解成本很低。
卡片除了展示数据本身,还做了简单的状态颜色映射,这样用户一眼就能读出当前环境是否舒适:
温度在18~26℃之间,主色用蓝色系;低于18℃用冷青色系;高于26℃用橙色系。
湿度在40%~60%之间,主色用绿色系;过干或过湿则显示灰色或蓝灰色。
这个逻辑在自定义组件内部通过 @Prop 接收外部的温度和湿度值,然后在 getColor() 方法里做判断返回。颜色变化时,数值文字、图标背景色、环形图主色都会联动变化,视觉反馈很直观。
注意:卡片和环形图处在同一个页面但属于不同子组件,温度颜色变化时,环形图和卡片需要同步更新。这里我给环形图也传入了当前值,在 @Watch 回调里触发重绘,避免出现卡片显示"舒适"但环形图颜色还是旧状态的情况。
温湿度数据的单位处理是个容易被忽略的细节。温度统一用摄氏度 °C ,湿度用相对湿度百分比 %RH 。因为传感器原始数据通常带有小数,我做了二次处理:
超过量程范围的数据直接裁剪到边界值,防止环形图弧线溢出。
格式化工具放在了一个独立的 FormatUtil 文件里,通过静态方法调用,页面和卡片组件都能公用。这种小工具类单独抽出来的好处是,以后接真实传感器时只需要替换数据层,展示层完全不用动。
3. 环形图实现:从数学原理到核心代码
环形图的本质是圆弧。先锚定几个基本概念,方便后面代码对齐:
startAngle :弧线起始角度,单位为度, 0 度对应3点钟方向,角度按顺时针方向增加。
sweepAngle :弧线扫过的角度范围,比如四分之三圆的 270 度就从起始点顺时针扫过270度。
为了让环形图看上去"缺个口"、更像仪表盘,我把起始角度设在 135 度(即5点钟方向),然后让弧线扫过 270 度,这样底部会留出一个90度的缺口,视觉重心更稳。
把角度换算成画布上的坐标,用三角函数:
其中 angle 要先从角度制转成弧度制,即 Math.PI * angle / 180 。这个公式在绘制刻度线、起点圆点、终点圆点的时候都会反复用到,建议直接封装成一个私有方法。
先看画布初始化。在 aboutToAppear 或者组件的初始化阶段,需要创建 RenderingContextSettings 和 CanvasRenderingContext2D 实例:
在 build 里声明Canvas组件时,显式设置宽高,并且在 onReady 回调中执行首次绘制:
接下来是核心的绘制方法。这里以温度环形图为例,值范围假设为 -10 到 50 摄氏度,当前温度通过方法参数传入:
这里有个细节: setLineCap('round') 会让圆弧两端呈现半圆头,看起来更圆润。但注意,使用 round 线帽后,绘制出来的弧线总长度会比实际路径多出两个半圆头的长度,起点和终点视觉上会轻微超出角度范围。所以如果你对圆弧长度有严格精度要求,比如仪器仪表类应用,就需要把 lineCap 改成 butt ,或者预先在数据上做微小修正。
实际业务中,数据映射不会只有上面这一种线性映射。我在这个项目里处理了三种场景:
固定量程线性映射:比如温度用 -10 到 50 ,湿度用 0 到 100 ,直接用上面的公式,最简单。
动态量程映射:比如传感器偶尔上报异常值,量程需要跟随数据源动态调整。这种情况不能写死 min 和 max ,需要在使用前根据最近一段时间的最大值和最小值计算量程,避免曲线长期停在100%或者0%。
带警告区间的分段映射:例如湿度低于30%属于干燥区,高于70%属于潮湿区,中间是舒适区。这种就不只是画一条弧线了,而是用三条不同颜色、不同起止角度的弧线拼接,对应标题里的"数据卡片与环形图"联动呈现。
当前版本做的是固定量程+动态颜色,后续如果有真实设备接入,可以在现有基础上扩展分段映射,代码结构已经预留好了。
这里给从Android转过来的朋友一段参考。Android的Java代码通常是:
鸿蒙的写法是链式设置属性,而且不需要自己管理 Paint 对象,绘制状态直接绑定在 CanvasRenderingContext2D 上。这有个好处:状态管理更集中,不容易出现Android里多个Paint混用导致属性串了的问题。但也有个坑:Canvas的绘制状态不是"可回退"的栈式结构,你画完前景环后如果不手动重新设置 strokeStyle 和 lineWidth ,下一个绘制元素会沿用之前的状态,容易在画文字或者刻度线时出现莫名粗线条。
建议:每次绘制不同元素前,显式设置 setStrokeStyle 、 setLineWidth 、 setFillStyle ,不要依赖默认值。虽然代码重复一点,但排查问题时会省很多时间。
环形图内部需要填充当前数值和单位,让图表信息自洽。这不能用Canvas的 fillText 直接写死位置,因为数值位数变化会导致文字宽度变化。我的做法:
setTextAlign('center') 和 setTextBaseline('middle') 分别控制水平和垂直对齐,这样不需要手动计算文字左上角坐标,直接给圆心坐标即可,省去很多偏移计算。
数值和单位分两行绘制,数值在上、单位在下。如果单位想放在数值右下角做"角标"效果,可以用 measureText 先量出数值宽度,再在对应坐标绘制文字。
4. 数据刷新与动画控制:让环形图"活"起来
真实项目里温湿度数据来自传感器或云端,这里先用定时器模拟,方便聚焦UI逻辑。在页面主体的 aboutToAppear 里启动定时器, aboutToDisappear 里清理,防止页面销毁后定时器还在跑、引发内存泄漏。
数据模拟时我给温度加了正弦波动,让数值在23℃上下浮动,湿度在50%左右浮动,不会出现突变,环形图动画过渡起来更自然。
温度和湿度是 @State 变量,子组件通过 @Prop 接收。环形图组件里监听数值变化:
@Watch 在值变化时自动触发 drawRing ,这样定时器更新数据后,环形图无需手动调用刷新方法。这是ArkUI状态管理比较舒服的一点,状态变了,UI自然跟着更新。
不过这里有一个性能细节要说明: @Watch 触发的重绘会直接操作Canvas,如果数据更新非常频繁(比如每100ms一次),Canvas的 clearRect 、 arc 、 stroke 操作会带来额外的CPU开销。在开发阶段实时刷新没有明显问题,但如果同时存在多个环形图,建议采用节流策略,把高频更新合并成一次绘制。
一般新手想到动画,第一反应是用 setInterval 每16ms刷新一次绘制。这在ArkUI里最大的问题是定时器精度不理想,尤其是页面不在前台或者系统负载高时,定时器回调会严重延迟甚至丢帧,动画观感非常差。
正确做法是用动画帧接口。在 @Watch 回调或者外部触发更新的时候,配合 animateTo 做组件级动画:
同时在 build 里通过 Canvas 级联属性或者 display 属性驱动重绘。不过如果想完全控制绘制细节,更推荐手动维护一个 progress 变量,结合 requestAnimationFrame 做插值:
这样做的好处是整个动画周期完全可控,任何时刻暂停、取消、改变插值函数都很容易。我实际测试下来,600ms的动画时长观感最自然,太短显得生硬,太长又会让人等得不耐烦。
环形图和卡片在手机上显示效果没问题,但折叠屏和平板上就要考虑尺寸限制。我把环形图的宽高和半径都定义为变量,在 aboutToAppear 里通过 display.getWindowDisplayInfo() 或者组件 onAreaChange 事件获取实际像素宽度,再换算成合理的画布尺寸。
这里要注意单位换算。ArkUI的布局单位是 vp ,但Canvas绘制使用的是 px 。如果直接用 this.context.arc(90, 90, 70, ...) ,在部分高密度屏幕上会出现图形偏小、锯齿明显的问题。我的做法是写一个工具方法:
然后用换算后的值作为绘制尺寸。这样无论在什么分辨率的设备上,环形图的物理大小基本保持一致。
这是初学者遇到最多的问题。归纳起来通常有两种原因:
Canvas组件本身没有宽度或高度。鸿蒙里如果只写了 Canvas(this.context) 而没有设置宽高,画布默认尺寸可能为0,绘制内容自然看不见。解决办法是显式声明宽高,或者用 aspectRatio 和父容器约束。
onReady 回调没有触发。 onReady 表示画布初始化完成,但如果组件被 if 条件包住且条件不满足,或者组件被放在了不在当前路由的页面里,都不会触发。排查时可以先在 onReady 里加一个打印日志,确认回调是否执行。
arc 接口的角度默认从3点钟方向开始,且按顺时针方向计算。如果想让环形图从12点方向或者仪表盘的左下角开始,必须手动做偏移。例如从12点方向开始就是 startAngle = -90 ,从5点钟方向开始就是 startAngle = 135 。
另外,弧线扫过的角度是顺时针还是逆时针,取决于 arc 的参数设置。鸿蒙的 arc 方法签名和HTML5 Canvas一致,最后一个参数如果传 false (默认)表示顺时针,传 true 表示逆时针。一定要确认自己的起点角度对应的扫角方向,否则会出现弧线"从终点倒着画回去"的诡异效果。
这个问题出现的原因是:绘制圆弧前笔触已经在某个位置, arc 会自动从当前位置到圆弧起点画一条连线。解决方法是每次绘制圆弧前先 beginPath() ,把上一段路径断开。同理,绘制完一段弧线后如果想画下一段,也要先 beginPath() ,否则两条线会被莫名其妙连起来。
这里要注意 radius 必须和绘制圆弧用的半径完全一致,而且 startAngle + currentSweep 要使用弧度制。最容易出错的点是在角度转弧度时漏掉 Math.PI / 180 ,导致圆点跑到了画布之外。建议把坐标换算封装成一个函数,反复使用,不要到处手写三角函数。
设置 setLineCap('round') 后,圆弧两端会多出半个线宽的圆形帽。圆形帽会向外延伸,视觉效果上圆环的起始和终点都会"超出"实际角度范围。比如绘制0~100%的完整圆环,首尾就会重叠出一个微小的凸起。解决方案是:
保留圆帽效果,把弧线的 startAngle 和 sweepAngle 做轻微内缩;
或者改用 setLineCap('butt') ,再单独绘制起点和终点的圆点。
两种方式我都测试过,如果追求轻量、工程感强的外观,推荐后者;如果追求圆润、可爱的视觉效果,用前者更合适。
闪烁的根源是绘制前没有清空画布,旧画面和新画面叠加导致跳动。每次 drawRing 方法开始前,一定要调用 clearRect(0, 0, width, height) 把整个画布擦干净。另一个细节是: clearRect 只清除矩形区域,如果绘制内容超出了画布边界,可能残留不可见区域,所以画布尺寸要比实际显示尺寸稍微大一点。
对于实时刷新的监测界面,Canvas绘制频率较高,要注意以下几点:
不要在 build 里创建频繁变化的对象。例如渐变对象 createLinearGradient ,每次绘制时创建的开销不大,但如果有多个环形图同时刷新,建议在初始化时创建并复用,避免频繁GC。
绘制前判断数据是否有变化。如果温湿度值跟上一次一样,就不需要重绘,直接return。
对于部分高端设备,可以开启硬件加速,但要注意测试兼容性,尤其是一些老设备上可能会出现文字模糊或弧线锯齿。
这个项目里数据卡片和环形图虽然显示同一份数据,但交互上是独立的。可以做一个更有意思的扩展:点击卡片时,页面中央的环形图切换展示对应的温度和湿度数据,并带有过渡动画。
实现思路很简单:页面维护一个 activeMetric 状态,卡片点击时修改该状态,环形图监听到状态变化后重新设置 min 、 max 、 value 和单位,调用 startAnimation 重绘。这样三个组件之间完全通过状态通信,符合ArkUI的单向数据流设计思想,代码清晰可维护。
当前定时器模拟的数据,可以换成蓝牙温湿度传感器或者HTTP轮询。真实数据接入时,建议在页面或者数据层增加一个缓冲数组,保留最近N组数据,用于绘制历史曲线或者滚动数据。环形图部分不变,只是数据来源从 setInterval 改为网络回调。
如果要画历史曲线,可以复用同样的Canvas思路:用 beginPath 和 moveTo 、 lineTo 画折线,或者用 bezierCurveTo 画平滑曲线。这块需要处理数据归一化和X轴缩放,整体复杂度比环形图高一些,但底子已经有了,扩展起来不费劲。
最后再分享一个小技巧:开发HarmonyOS Next界面时,尽量多利用 @Preview 装饰器在IDE里预览组件效果。我调试环形图的配色和角度时,就是在预览器里一边调 startAngle 和渐变颜色、一边看效果,比每次都要跑到模拟器上快很多,尤其适合纯UI阶段的快速迭代。整个课程做到这里,我对ArkUI的声明式UI和Canvas绘制的理解已经比只看文档时深了一个层次,后面再做图表类页面,直接手绘也比引入第三方库更安心。

本文来源:https://www.hqwc.cn/a/1771455.html
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。
Anyone building smart-home or environmental-monitoring apps cannot avoid a temperature and humidity panel. This lesson records my complete process implementing such an interface on HarmonyOS Next, centered on two technical points: data cards and ring charts. The cards use ArkUI's declarative layout, while the ring charts are hand-drawn from scratch with the Canvas component, including ticks, gradient arcs, central values, and animated transitions. If you are working on Harmony OS app development, especially trying to understand Canvas drawing, animation driving, and component lifecycle coordination, you can follow this directly.
The final effect: two data cards at the top show current temperature and humidity, each with an icon, value, unit, and status description; below are two ring charts, temperature on the left and humidity on the right, with arc length representing the value's share of the range and gradient colors plus dots at the arc ends. Data is simulated by a timer reporting sensor readings, and switching pages or tapping a card replays a transition animation.
In the HarmonyOS Next ecosystem, chart libraries are not plentiful: established libraries such as MPAndroidChart are either not portable to Harmony OS or not actively maintained, and forced adaptation may cost more than writing your own. A ring chart is not structurally complex, essentially a ring with a gap and an arc showing progress, which Canvas handles completely, saving the package size, compatibility, and learning cost of a dependency. Another consideration is that HarmonyOS's Canvas interfaces share lineage with Web Canvas and Android Canvas, so anyone familiar with either can migrate easily. I will list all the APIs and math conversions used, and the entry barrier is low if you follow the steps.
The top level uses a Column for vertical layout, controlling overall margins and alignment; the middle is a 2x2 grid area using Row to arrange two columns with the cards and ring charts; the bottom is data-refresh logic using setInterval to simulate sensor sampling and @State to drive UI updates. The reason for wrapping cards and ring charts in separate @Components is to control the render scope when state changes: temperature changes once per second, and although HarmonyOS's diff algorithm can skip unchanged parts, shrinking the refresh granularity to child components makes the code clearer and lets you reuse the temperature card or humidity ring chart independently later.
Since a hot search topic reads 'Android Studio custom View ring chart with a complete Java example,' many people clearly want cross-platform comparison. The difference is brief. Android custom View requires extending View, overriding onMeasure and onDraw, drawing with Paint plus Canvas, plus a bundle of related knowledge such as custom attributes and MeasureSpec. HarmonyOS Next's ArkUI moves the UI description into build, declares the canvas with Canvas(this.context), obtains a CanvasRenderingContext2D in the onReady callback, and the drawing logic is almost identical to Android's Canvas API: beginPath(), arc(), stroke(), and fill() all have the same names.
So if you have written an Android ring chart before, the learning curve to Harmony OS is gentle. The main differences: Harmony OS uses RenderingContextSettings for anti-aliasing, drawing lengths need vp-to-px conversion, and animation cannot rely on invalidate() but must use Canvas's own animation-frame interfaces, all of which are handled in the code below.
2. Building the data cards: the core layout of the monitoring panel
For the cards I referenced the rounded-card scheme often seen in official Harmony OS examples, avoiding overly complex strokes or layered shadows. The basic card style: background color #FFFFFF, pure white to distinguish it from the page's light-gray background; 16vp corner radius with a light shadow via the shadow property to keep the page from looking too flat; padding of 16vp left and right and 14vp top and bottom so content does not touch the edges. Structurally each card splits in two: icon and label text on the left, value and unit on the right, with the value in a large font and the unit in a small gray font above or next to the value.
One detail: the temperature and humidity cards use different icons and main colors. I used Flex layout to vertically center the icon and text, avoiding manual margin tweaks; HarmonyOS's Flex justifyContent and alignItems are nearly identical to CSS Flexbox, so the learning cost is low. Beyond displaying data, the cards also do simple status color mapping so users can tell at a glance whether the environment is comfortable: temperature between 18 and 26C uses a blue palette, below 18C a cool cyan, above 26C orange; humidity between 40% and 60% uses green, while too dry or too damp shows gray or blue-gray.
This logic lives inside the custom component, receiving external temperature and humidity values via @Prop and returning a color from a getColor() method. When the color changes, the value text, icon background, and ring chart's main color all update together for intuitive feedback. Note that the card and ring chart are on the same page but are different child components: when temperature color changes, both must update in sync, so I also pass the current value into the ring chart and trigger a redraw in an @Watch callback, avoiding a state where the card says 'comfortable' but the ring chart still shows the old color.
Unit handling is an easily overlooked detail: temperature is uniformly in degrees Celsius and humidity in relative humidity percentage. Since raw sensor data usually has decimals, I added secondary processing: data outside the range is clipped to the boundary to prevent the arc from overflowing. The formatting utility sits in a separate FormatUtil file and is called via static methods so both the page and card components can share it. The benefit of extracting such a small utility is that when you later connect a real sensor you only replace the data layer, leaving the presentation layer untouched.
3. Implementing the ring chart: from math to core code
A ring chart is essentially an arc. Let us anchor a few concepts so the code lines up. startAngle is the arc's starting angle in degrees, with 0 degrees at the 3 o'clock position and angles increasing clockwise. sweepAngle is the angular range the arc covers, so a three-quarter circle sweeps 270 degrees clockwise from the start. To make the chart look like it has a gap, more like a gauge, I set the start angle to 135 degrees (5 o'clock) and sweep 270 degrees, leaving a 90-degree gap at the bottom for a more stable visual center.
Converting angles to canvas coordinates uses trigonometry, with the angle first converted from degrees to radians via Math.PI * angle / 180. This formula is used repeatedly when drawing tick lines, start dots, and end dots, so it is best wrapped in a private method. For canvas initialization, in aboutToAppear or the component's init phase you create RenderingContextSettings and CanvasRenderingContext2D instances; when declaring the Canvas in build, set width and height explicitly and perform the first draw in onReady.
The core drawing method, taking the temperature ring as an example, assumes a range of -10 to 50 degrees with the current temperature passed as a parameter. A detail: setLineCap('round') makes the arc ends semicircular and look softer, but with a round cap the drawn arc is longer than the actual path by two half-caps, so the start and end visually exceed the angular range slightly. If you need strict precision, such as instrumentation, change lineCap to butt or pre-correct the data slightly.
In real business, data mapping is not always this simple linear case. I handled three scenarios in this project: fixed-range linear mapping, such as -10 to 50 for temperature and 0 to 100 for humidity, using the formula above directly. Dynamic-range mapping, where the sensor occasionally reports abnormal values and the range must track the data source; you cannot hardcode min and max but must compute the range from recent maxima and minima before use, so the curve does not sit permanently at 100% or 0%. Segmented mapping with warning bands, for example humidity below 30% is dry, above 70% damp, and in between comfortable; this is no longer a single arc but three arcs of different colors and start/end angles, corresponding to the 'data card and ring chart' linkage in the title. The current version uses fixed range plus dynamic color, with room reserved in the code structure to add segmented mapping when real devices arrive.
For friends coming from Android, here is a reference. Android Java code is usually chained property settings and does not require managing Paint objects yourself; drawing state is bound directly to CanvasRenderingContext2D. This centralized state management avoids Android's problem of attribute bleed from multiple Paint objects, but there is a trap: Canvas drawing state is not a reversible stack, so after drawing the foreground ring, if you do not reset strokeStyle and lineWidth, the next element inherits the previous state and you get mysteriously thick lines when drawing text or ticks. My advice: explicitly call setStrokeStyle, setLineWidth, and setFillStyle before drawing each different element rather than relying on defaults; a bit more repetition saves a lot of debugging time.
The ring's interior must show the current value and unit so the chart is self-contained. You cannot use Canvas fillText with fixed positions because digit-count changes alter text width. My approach: setTextAlign('center') and setTextBaseline('middle') control horizontal and vertical alignment, so you just pass the center coordinates without manually computing the top-left corner. Value and unit are drawn on two lines, value above and unit below; if you want the unit as a small subscript at the lower right of the value, use measureText to get the value width first and then draw at the corresponding coordinates.
4. Data refresh and animation: bringing the ring chart to life
In real projects temperature and humidity come from sensors or the cloud; here a timer simulates them so we can focus on UI logic. Start the timer in the page's aboutToAppear and clear it in aboutToDisappear to avoid memory leaks after the page is destroyed. In the simulation I add a sine wave to temperature so values float around 23C and humidity around 50%, avoiding abrupt jumps and making the ring animation more natural. Temperature and humidity are @State variables received by child components via @Prop; the ring component watches value changes, and @Watch automatically triggers drawRing, so after the timer updates data the ring redraws without a manual call. That is one of the comfortable parts of ArkUI state management: when state changes, UI follows.
There is a performance detail to note: @Watch-triggered redraws operate directly on Canvas, and if data updates very frequently (say every 100ms), clearRect, arc, and stroke add CPU overhead. Real-time refresh is fine in development, but with multiple ring charts consider throttling to merge high-frequency updates into one draw. When beginners think of animation, the first idea is setInterval every 16ms; in ArkUI the biggest problem is imprecise timer callbacks, especially when the page is not in the foreground or system load is high, causing serious delays or dropped frames and poor visuals.
The correct approach is the animation-frame interface: in an @Watch callback or external trigger, use animateTo for component-level animation, and drive redraws through Canvas cascade properties or the display property in build. For full control over drawing details, it is better to maintain a progress variable and use requestAnimationFrame for interpolation. This makes the entire animation cycle controllable, so pausing, canceling, or changing the interpolation function at any moment is easy. In my tests a 600ms animation duration felt most natural: too short is abrupt, too long makes people impatient.
The ring and cards display fine on a phone, but foldables and tablets require size handling. I define the ring's width, height, and radius as variables and obtain the actual pixel width in aboutToAppear via display.getWindowDisplayInfo() or the component's onAreaChange event, then convert to a sensible canvas size. Mind the unit conversion: ArkUI layout uses vp while Canvas drawing uses px; if you directly call this.context.arc(90, 90, 70, ...) on some high-density screens the shape will look small and jagged. My approach is a utility method that converts units and then using the converted values as drawing sizes, so the ring's physical size stays roughly consistent across resolutions.
Common pitfalls for beginners generally fall into a few categories. First, the Canvas component has no width or height: if you only write Canvas(this.context) without setting dimensions, the default size may be zero and nothing is visible; declare width and height explicitly or constrain it with aspectRatio and the parent. Second, the onReady callback does not fire: onReady means the canvas is initialized, but if the component is wrapped in an if whose condition is false, or sits on a page not in the current route, it will not fire; add a log in onReady first to confirm. Third, arc angles: the arc interface starts at 3 o'clock and increases clockwise by default; to start at 12 o'clock use startAngle = -90, and from 5 o'clock use startAngle = 135. Fourth, sweep direction depends on the arc parameters; Harmony OS's signature matches HTML5 Canvas, where the last parameter false (default) means clockwise and true counterclockwise, so confirm your start angle matches the sweep direction or the arc will draw backward from the end.
Another issue arises because the pen is already somewhere before drawing an arc, and arc automatically draws a connecting line from the current position to the arc's start; call beginPath() before each arc to break the previous path, and likewise before drawing the next segment after finishing one. The end dot's radius must exactly match the arc's radius, and startAngle + currentSweep must be in radians; the easiest mistake is forgetting Math.PI / 180 when converting, sending the dot outside the canvas, so wrap the coordinate conversion in a reusable function rather than writing trigonometry everywhere.
With setLineCap('round'), each arc end gains a semicircular cap of half the line width, extending outward so the start and end visually exceed the actual range; drawing a full 0-100% ring will overlap into a small bump at the seam. Solutions: keep the round cap but slightly inset startAngle and sweepAngle, or switch to setLineCap('butt') and draw the start and end dots separately. I have tested both: for a light, engineering look prefer the latter, for a rounded, cute look the former.
Flicker comes from not clearing the canvas before drawing, so old and new frames overlap. Call clearRect(0, 0, width, height) at the start of every drawRing to wipe the whole canvas. Another detail: clearRect clears only a rectangular area, and content drawn outside the canvas boundary may leave invisible residue, so make the canvas slightly larger than the actual display size. For a frequently refreshing monitoring interface, avoid creating frequently changing objects in build, such as createLinearGradient; a single gradient is cheap but with multiple rings refreshing together it is better to create once at init and reuse to avoid frequent GC. Check whether data actually changed before drawing and return early if temperature and humidity match the previous values. Some high-end devices support hardware acceleration, but test compatibility, as older devices may show blurry text or jagged arcs.
As an extension, the cards and ring chart show the same data but are independent in interaction. A more interesting idea: tapping a card makes the central ring switch to the corresponding temperature or humidity data with a transition animation. The implementation is simple: maintain an activeMetric state on the page, change it on card taps, and when the ring observes the state change it resets min, max, value, and unit and calls startAnimation to redraw. All three components communicate purely through state, following ArkUI's unidirectional data flow, so the code is clear and maintainable.
The timer-simulated data can be replaced with a Bluetooth temperature and humidity sensor or HTTP polling. When connecting real data, add a buffer array on the page or data layer to keep the last N readings for historical curves or rolling data, leaving the ring part unchanged and only switching the source from setInterval to a network callback. To draw a historical curve you can reuse the same Canvas approach: beginPath with moveTo and lineTo for a polyline, or bezierCurveTo for a smooth curve. This requires data normalization and X-axis scaling, a bit more complex than the ring, but the foundation is already there. Finally, a tip: when developing HarmonyOS Next UI, use the @Preview decorator in the IDE to preview components. While debugging the ring's colors and angles I adjusted startAngle and gradient colors in the preview while watching the result, much faster than running the simulator each time, especially for rapid UI iteration. Reaching this point in the course, my understanding of ArkUI's declarative UI and Canvas drawing is a level deeper than reading docs alone, and for chart pages later I am more comfortable drawing by hand than pulling in a third-party library.