#跟着若城学鸿蒙# 自定义圆环组件(Ring)
·
在 ArkUI 中,自定义圆环既可通过现有组件组合,也可借助 Canvas 进行精确绘制。本文分三部分介绍:组合方式、Canvas 方式与属性封装,并附上完整示例,帮助你快速掌握自定义组件传值与生命周期钩子。
1. 组合方式
最简单的圆环由两个 Circle 叠放实现:
@Component export struct Ring {
build() {
Stack({ alignContent: Alignment.Center }) {
Circle()
.width('100%').height('100%')
.fill(this.ringAttribute.color)
Circle()
.width((this.ringAttribute.radius * 2 - this.ringAttribute.width))
.height((this.ringAttribute.radius * 2 - this.ringAttribute.width))
.fill(this.ringAttribute.solid)
}
.width(this.ringAttribute.radius * 2)
.height(this.ringAttribute.radius * 2)
}
}
利用 Stack 居中大圆(环体)和小圆(内填充),无需手工绘制。
2. 属性封装
继承组合方式无法灵活定制尺寸与颜色,我们定义 RingAttribute:
class RingAttribute {
radius: number = 45;
width: number = 5;
color: Color | number | string | Resource = '#000000';
solid: Color | number | string | Resource = '#ffffff';
static filter(attr?: RingAttribute): RingAttribute {
const def = new RingAttribute();
if (!attr) return def;
return {
radius: attr.radius ?? def.radius,
width: attr.width ?? def.width,
color: attr.color ?? def.color,
solid: attr.solid ?? def.solid
};
}
}
通过 aboutToAppear() 钩子校验并填充默认值:
private aboutToAppear() {
this.ringAttribute = RingAttribute.filter(this.ringAttribute);
}
外部即可在组件构造时传入任意组合参数。
3. Canvas 绘制方式
若需绘制不规则弧度或渐变,可改用 Canvas:
@Component export struct Ring {
private settings = new RenderingContextSettings(true);
private context = new CanvasRenderingContext2D(this.settings);
build() {
Canvas(this.context)
.width(this.ringAttribute.radius * 2)
.height(this.ringAttribute.radius * 2)
.onReady(() => {
const ctx = this.context;
ctx.strokeStyle = this.ringAttribute.color.toString();
ctx.lineWidth = this.ringAttribute.width;
ctx.beginPath();
ctx.arc(
this.ringAttribute.radius,
this.ringAttribute.radius,
this.ringAttribute.radius - this.ringAttribute.width/2,
0, 2 * Math.PI
);
ctx.stroke();
});
}
private aboutToAppear() {
this.ringAttribute = RingAttribute.filter(this.ringAttribute);
}
}
在 onReady 回调中,arc() 方法能画出任意弧线,精度更高。
4. 使用示例
import {Ring} from './widgets/ring';
@Entry @Component struct Demo {
build() {
Row({ space: 10 }) {
Ring() // 默认圆环
Ring({ ringAttribute: {
radius: 40, width: 8,
color: Color.Green, solid: '#aabbcc'
}})
Ring({ ringAttribute: {
radius: 50, width: 12,
color: Color.Red, solid: Color.Pink
}})
}
}
}
只需在构造调用时传入 ringAttribute 对象,即可动态调整半径、宽度与色彩。
通过上述三种方式,你可以在 ArkUI 中轻松实现可自定义的环形进度条或装饰性圆环组件,并掌握组件参数过滤、生命周期钩子与 Canvas 绘制结合的高级用法。期待你基于此继续扩展渐变、动画等特性,为你的应用界面增色添彩!
更多推荐




所有评论(0)