HarmonyOS/OpenHarmony元服务开发-卡片使用自定义绘制能力

ArkTS卡片开放了自定义绘制的能力,在卡片上可以通过Canvas组件创建一块画布,然后通过CanvasRenderingContext2D对象在画布上进行自定义图形的绘制,如下示例代码实现了在画布的中心绘制了一个笑脸。

复制代码
@Entry
@Component
struct Card {
private canvasWidth: number = 0;
private canvasHeight: number = 0;
// 初始化CanvasRenderingContext2D和RenderingContextSettings
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);

build() {
Column() {
Row() {
Canvas(this.context)
.margin('5%')
.width('90%')
.height('90%')
.onReady(() => {
console.info('[ArkTSCard] onReady for canvas draw content');
// 在onReady回调中获取画布的实际宽和高
this.canvasWidth = this.context.width;
this.canvasHeight = this.context.height;
// 绘制画布的背景
this.context.fillStyle = 'rgba(203, 154, 126, 1.00)';
this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
// 在画布的中心绘制一个红色的圆
this.context.beginPath();
let radius = this.context.width / 3
let circleX = this.context.width / 2
let circleY = this.context.height / 2
this.context.moveTo(circleX - radius, circleY);
this.context.arc(circleX, circleY, radius, 2 * Math.PI, 0, true);
this.context.closePath();
this.context.fillStyle = 'red';
this.context.fill();
// 绘制笑脸的左眼
let leftR = radius / 4
let leftX = circleX - (radius / 2)
let leftY = circleY - (radius / 3.5)
this.context.beginPath();
this.context.arc(leftX, leftY, leftR, 0, Math.PI, true);
this.context.strokeStyle = '#ffff00'
this.context.lineWidth = 10
this.context.stroke()
// 绘制笑脸的右眼
let rightR = radius / 4
let rightX = circleX + (radius / 2)
let rightY = circleY - (radius / 3.5)
this.context.beginPath();
this.context.arc(rightX, rightY, rightR, 0, Math.PI, true);
this.context.strokeStyle = '#ffff00'
this.context.lineWidth = 10
this.context.stroke()
// 绘制笑脸的嘴巴
let mouthR = radius / 2.5
let mouthX = circleX
let mouthY = circleY + (radius / 3)
this.context.beginPath();
this.context.arc(mouthX, mouthY, mouthR, Math.PI, 0, true);
this.context.strokeStyle = '#ffff00'
this.context.lineWidth = 10
this.context.stroke()
})
}
}.height('100%').width('100%')
}
}
相关推荐
xianjixiance_2 小时前
Flutter跨平台三方库鸿蒙化适配指南
flutter·华为·harmonyos
夏小鱼的blog2 小时前
【HarmonyOS应用开发入门】第四期:ArkTS语言基础(二)
harmonyos·openharmony
wtrees_松阳3 小时前
【弦断九章·CPU篇】鸿蒙应用性能优化心法
华为·性能优化·harmonyos
2501_946224313 小时前
旅行记录应用统计分析 - Cordova & OpenHarmony 混合开发实战
javascript·harmonyos·harvester
2501_946224314 小时前
旅行记录应用外观设置 - Cordova & OpenHarmony 混合开发实战
javascript·harmonyos·harvester
TAEHENGV5 小时前
回收站模块 Cordova 与 OpenHarmony 混合开发实战
android·java·harmonyos
Nick不懂7 小时前
鸿蒙分布式KVStore冲突解决机制:原理、实现与工程化实践
harmonyos
FrameNotWork7 小时前
深入浅出 HarmonyOS NEXT (迈向 6.0 架构):攻克 ArkTS 高性能状态管理与 NAPI 底层交互难题
架构·交互·harmonyos
个案命题8 小时前
鸿蒙ArkUI状态管理新宠:@Local装饰器全方位解析与实战
microsoft·华为·harmonyos
luxy20049 小时前
【鸿蒙开发实战】HarmonyOS单词库应用
华为·harmonyos