介紹
本篇Codelab是基于畫(huà)布組件、顯式動(dòng)畫(huà),實(shí)現(xiàn)的一個(gè)自定義抽獎(jiǎng)圓形轉(zhuǎn)盤(pán)。包含如下功能:
- 通過(guò)畫(huà)布組件Canvas,畫(huà)出抽獎(jiǎng)圓形轉(zhuǎn)盤(pán)。
- 通過(guò)顯式動(dòng)畫(huà)啟動(dòng)抽獎(jiǎng)功能。
- 通過(guò)自定義彈窗彈出抽中的獎(jiǎng)品。

相關(guān)概念
- [Stack組件]:堆疊容器,子組件按照順序依次入棧,后一個(gè)子組件覆蓋前一個(gè)子組件。
- [Canvas]:畫(huà)布組件,用于自定義繪制圖形。
- [CanvasRenderingContext2D對(duì)象]:使用RenderingContext在Canvas組件上進(jìn)行繪制,繪制對(duì)象可以是矩形、文本、圖片等。
- [顯式動(dòng)畫(huà)]:提供全局animateTo顯式動(dòng)畫(huà)接口來(lái)指定由于閉包代碼導(dǎo)致的狀態(tài)變化插入過(guò)渡動(dòng)效。
- [自定義彈窗]: 通過(guò)CustomDialogController類(lèi)顯示自定義彈窗。
環(huán)境搭建
軟件要求
- [DevEco Studio]版本:DevEco Studio 3.1 Release。
- OpenHarmony SDK版本:API version 9。
硬件要求
- 開(kāi)發(fā)板類(lèi)型:[潤(rùn)和RK3568開(kāi)發(fā)板]。
- OpenHarmony系統(tǒng):3.2 Release。
環(huán)境搭建
完成本篇Codelab我們首先要完成開(kāi)發(fā)環(huán)境的搭建,本示例以RK3568開(kāi)發(fā)板為例,參照以下步驟進(jìn)行:
- [獲取OpenHarmony系統(tǒng)版本]:標(biāo)準(zhǔn)系統(tǒng)解決方案(二進(jìn)制)。以3.2 Release版本為例:

- 搭建燒錄環(huán)境。
- [完成DevEco Device Tool的安裝]
- [完成RK3568開(kāi)發(fā)板的燒錄](méi)
- 搭建開(kāi)發(fā)環(huán)境。
代碼結(jié)構(gòu)解讀
本篇Codelab只對(duì)核心代碼進(jìn)行講解,對(duì)于完整代碼,我們會(huì)在gitee中提供。
├──entry/src/main/ets // 代碼區(qū)
│ ├──common
│ │ ├──constants
│ │ │ ├──ColorConstants.ets // 顏色常量類(lèi)
│ │ │ ├──CommonConstants.ets // 公共常量類(lèi)
│ │ │ └──StyleConstants.ets // 樣式常量類(lèi)
│ │ └──utils
│ │ ├──CheckEmptyUtils.ets // 數(shù)據(jù)判空工具類(lèi)
│ │ └──Logger.ets // 日志打印類(lèi)
│ ├──entryability
│ │ └──EntryAbility.ts // 程序入口類(lèi)
│ ├──pages
│ │ └──CanvasPage.ets // 主界面
│ ├──view
│ │ └──PrizeDialog.ets // 中獎(jiǎng)信息彈窗類(lèi)
│ └──viewmodel
│ ├──DrawModel.ets // 畫(huà)布相關(guān)方法類(lèi)
│ ├──FillArcData.ets // 繪制圓弧數(shù)據(jù)實(shí)體類(lèi)
│ └──PrizeData.ets // 中獎(jiǎng)信息實(shí)體類(lèi)
└──entry/src/main/resources // 資源文件目錄
`HarmonyOS與OpenHarmony鴻蒙文檔籽料:mau123789是v直接拿`

構(gòu)建主界面
在這個(gè)章節(jié)中,我們將完成示例主界面的開(kāi)發(fā),效果如圖所示:

在繪制抽獎(jiǎng)圓形轉(zhuǎn)盤(pán)前,首先需要在CanvasPage.ets的aboutToAppear()方法中獲取屏幕的寬高。
// CanvasPage.ets
// 獲取context
let context = getContext(this);
aboutToAppear() {
// 獲取屏幕的寬高
window.getLastWindow(context)
.then((windowClass) = > {
let windowProperties = windowClass.getWindowProperties();
this.screenWidth = px2vp(windowProperties.windowRect.width);
this.screenHeight = px2vp(windowProperties.windowRect.height);
})
.catch((error: Error) = > {
Logger.error('Failed to obtain the window size. Cause: ' + JSON.stringify(error));
})
}
在CanvasPage.ets布局界面中添加Canvas組件,在onReady()方法中進(jìn)行繪制。
// CanvasPage.ets
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private canvasContext: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
Stack({ alignContent: Alignment.Center }) {
Canvas(this.canvasContext)
...
.onReady(() = > {
// 通過(guò)draw方法進(jìn)行繪制
this.drawModel.draw(this.canvasContext, this.screenWidth, this.screenHeight);
})
// 開(kāi)始抽獎(jiǎng)圖片
Image($r('app.media.ic_center'))
...
}
...
在DrawModel.ets中,通過(guò)draw()方法逐步進(jìn)行自定義圓形抽獎(jiǎng)轉(zhuǎn)盤(pán)的繪制。
// DrawModel.ets
// 畫(huà)抽獎(jiǎng)圓形轉(zhuǎn)盤(pán)
draw(canvasContext: CanvasRenderingContext2D, screenWidth: number, screenHeight: number) {
if (CheckEmptyUtils.isEmptyObj(canvasContext)) {
Logger.error('[DrawModel][draw] canvasContext is empty.');
return;
}
this.canvasContext= canvasContext;
this.screenWidth = screenWidth;
this.canvasContext.clearRect(0, 0, this.screenWidth, screenHeight);
// 將畫(huà)布沿X、Y軸平移指定距離
this.canvasContext.translate(this.screenWidth / CommonConstants.TWO,
screenHeight / CommonConstants.TWO);
// 畫(huà)外部圓盤(pán)的花瓣
this.drawFlower();
// 畫(huà)外部圓盤(pán)、小圈圈
this.drawOutCircle();
// 畫(huà)內(nèi)部圓盤(pán)
this.drawInnerCircle();
// 畫(huà)內(nèi)部扇形抽獎(jiǎng)區(qū)域
this.drawInnerArc();
// 畫(huà)內(nèi)部扇形區(qū)域文字
this.drawArcText();
// 畫(huà)內(nèi)部扇形區(qū)域獎(jiǎng)品對(duì)應(yīng)的圖片
this.drawImage();
this.canvasContext.translate(-this.screenWidth / CommonConstants.TWO,
-screenHeight / CommonConstants.TWO);
}
畫(huà)外部圓盤(pán)
畫(huà)外部圓盤(pán)的花瓣:通過(guò)調(diào)用rotate()方法,將畫(huà)布旋轉(zhuǎn)指定角度。再通過(guò)調(diào)用save()和restore()方法,使畫(huà)布保存最新的繪制狀態(tài)。根據(jù)想要繪制的花瓣個(gè)數(shù),改變旋轉(zhuǎn)角度,循環(huán)畫(huà)出花瓣效果。
// DrawModel.ets
// 畫(huà)外部圓盤(pán)的花瓣
drawFlower() {
let beginAngle = this.startAngle + this.avgAngle;
const pointY = this.screenWidth * CommonConstants.FLOWER_POINT_Y_RATIOS;
const radius = this.screenWidth * CommonConstants.FLOWER_RADIUS_RATIOS;
const innerRadius = this.screenWidth * CommonConstants.FLOWER_INNER_RATIOS;
for (let i = 0; i < CommonConstants.COUNT; i++) {
this.canvasContext?.save();
this.canvasContext?.rotate(beginAngle * Math.PI / CommonConstants.HALF_CIRCLE);
this.fillArc(new FillArcData(0, -pointY, radius, 0, Math.PI * CommonConstants.TWO),
ColorConstants.FLOWER_OUT_COLOR);
this.fillArc(new FillArcData(0, -pointY, innerRadius, 0, Math.PI * CommonConstants.TWO),
ColorConstants.FLOWER_INNER_COLOR);
beginAngle += this.avgAngle;
this.canvasContext?.restore();
}
}
// 畫(huà)弧線(xiàn)方法
fillArc(fillArcData: FillArcData, fillColor: string) {
if (CheckEmptyUtils.isEmptyObj(fillArcData) || CheckEmptyUtils.isEmptyStr(fillColor)) {
Logger.error('[DrawModel][fillArc] fillArcData or fillColor is empty.');
return;
}
if (this.canvasContext !== undefined) {
this.canvasContext.beginPath();
this.canvasContext.fillStyle = fillColor;
this.canvasContext.arc(fillArcData.x, fillArcData.y, fillArcData.radius,
fillArcData.startAngle, fillArcData.endAngle);
this.canvasContext.fill();
}
}
畫(huà)外部圓盤(pán)、圓盤(pán)邊上的小圈圈:在指定的X、Y(0, 0)坐標(biāo)處,畫(huà)一個(gè)半徑為this.screenWidth * CommonConstants.OUT_CIRCLE_RATIOS的圓形。接下來(lái)通過(guò)一個(gè)for循環(huán),且角度每次遞增CommonConstants.CIRCLE / CommonConstants.SMALL_CIRCLE_COUNT,來(lái)繪制圓環(huán)上的小圈圈。
// DrawModel.ets
drawOutCircle() {
// 畫(huà)外部圓盤(pán)
this.fillArc(new FillArcData(0, 0, this.screenWidth * CommonConstants.OUT_CIRCLE_RATIOS, 0,
Math.PI * CommonConstants.TWO), ColorConstants.OUT_CIRCLE_COLOR);
let beginAngle = this.startAngle;
// 畫(huà)小圓圈
for (let i = 0; i < CommonConstants.SMALL_CIRCLE_COUNT; i++) {
this.canvasContext?.save();
this.canvasContext?.rotate(beginAngle * Math.PI / CommonConstants.HALF_CIRCLE);
this.fillArc(new FillArcData(this.screenWidth * CommonConstants.SMALL_CIRCLE_RATIOS, 0,
CommonConstants.SMALL_CIRCLE_RADIUS, 0, Math.PI * CommonConstants.TWO),
ColorConstants.WHITE_COLOR);
beginAngle = beginAngle + CommonConstants.CIRCLE / CommonConstants.SMALL_CIRCLE_COUNT;
this.canvasContext?.restore();
}
}
畫(huà)內(nèi)部扇形抽獎(jiǎng)區(qū)域
畫(huà)內(nèi)部圓盤(pán)、內(nèi)部扇形抽獎(jiǎng)區(qū)域:使用fillArc()方法繪制內(nèi)部圓盤(pán)。通過(guò)一個(gè)for循環(huán),角度每次遞增this.avgAngle。然后不斷更改弧線(xiàn)的起始弧度this.startAngle * Math.PI / CommonConstants.HALF_CIRCLE和弧線(xiàn)的終止弧度(this.startAngle + this.avgAngle) * Math.PI / CommonConstants.HALF_CIRCLE。最后用fill()方法對(duì)路徑進(jìn)行填充。
// DrawModel.ets
// 畫(huà)內(nèi)部圓盤(pán)
drawInnerCircle() {
this.fillArc(new FillArcData(0, 0, this.screenWidth * CommonConstants.INNER_CIRCLE_RATIOS, 0,
Math.PI * CommonConstants.TWO), ColorConstants.INNER_CIRCLE_COLOR);
this.fillArc(new FillArcData(0, 0, this.screenWidth * CommonConstants.INNER_WHITE_CIRCLE_RATIOS, 0,
Math.PI * CommonConstants.TWO), ColorConstants.WHITE_COLOR);
}
// 畫(huà)內(nèi)部扇形抽獎(jiǎng)區(qū)域
drawInnerArc() {
// 顏色集合
let colors = [
ColorConstants.ARC_PINK_COLOR, ColorConstants.ARC_YELLOW_COLOR,
ColorConstants.ARC_GREEN_COLOR, ColorConstants.ARC_PINK_COLOR,
ColorConstants.ARC_YELLOW_COLOR, ColorConstants.ARC_GREEN_COLOR
];
let radius = this.screenWidth * CommonConstants.INNER_ARC_RATIOS;
for (let i = 0; i < CommonConstants.COUNT; i++) {
this.fillArc(new FillArcData(0, 0, radius, this.startAngle * Math.PI / CommonConstants.HALF_CIRCLE,
(this.startAngle + this.avgAngle) * Math.PI / CommonConstants.HALF_CIRCLE), colors[i]);
this.canvasContext?.lineTo(0, 0);
this.canvasContext?.fill();
this.startAngle += this.avgAngle;
}
}
畫(huà)內(nèi)部抽獎(jiǎng)區(qū)域文字:用for循環(huán),通過(guò)drawCircularText()方法繪制每組文字。drawCircularText()方法接收三個(gè)參數(shù),分別是字符串,起始弧度和終止弧度。繪制文本前需要設(shè)置每個(gè)字母占的弧度angleDecrement,然后設(shè)置水平和垂直的偏移量。垂直偏移量circleText.y - Math.sin(angle) * radius就是朝著圓心移動(dòng)的距離;水平偏移circleText.x + Math.cos(angle) * radius,是為了讓文字在當(dāng)前弧范圍文字居中。最后使用fillText()方法繪制文本。
// DrawModel.ets
// 畫(huà)內(nèi)部扇形區(qū)域文字
drawArcText() {
if (this.canvasContext !== undefined) {
this.canvasContext.textAlign = CommonConstants.TEXT_ALIGN;
this.canvasContext.textBaseline = CommonConstants.TEXT_BASE_LINE;
this.canvasContext.fillStyle = ColorConstants.TEXT_COLOR;
this.canvasContext.font = StyleConstants.ARC_TEXT_SIZE + CommonConstants.CANVAS_FONT;
}
// 需要繪制的文本數(shù)組集合
let textArrays = [
$r('app.string.text_smile'),
$r('app.string.text_hamburger'),
$r('app.string.text_cake'),
$r('app.string.text_smile'),
$r('app.string.text_beer'),
$r('app.string.text_watermelon')
];
let arcTextStartAngle = CommonConstants.ARC_START_ANGLE;
let arcTextEndAngle = CommonConstants.ARC_END_ANGLE;
for (let i = 0; i < CommonConstants.COUNT; i++) {
this.drawCircularText(this.getResourceString(textArrays[i]),
(this.startAngle + arcTextStartAngle) * Math.PI / CommonConstants.HALF_CIRCLE,
(this.startAngle + arcTextEndAngle) * Math.PI / CommonConstants.HALF_CIRCLE);
this.startAngle += this.avgAngle;
}
}
// 繪制圓弧文本
drawCircularText(textString: string, startAngle: number, endAngle: number) {
if (CheckEmptyUtils.isEmptyStr(textString)) {
Logger.error('[DrawModel][drawCircularText] textString is empty.');
return;
}
class CircleText {
x: number = 0;
y: number = 0;
radius: number = 0;
}
let circleText: CircleText = {
x: 0,
y: 0,
radius: this.screenWidth * CommonConstants.INNER_ARC_RATIOS
};
// 圓的半徑
let radius = circleText.radius - circleText.radius / CommonConstants.COUNT;
// 每個(gè)字母占的弧度
let angleDecrement = (startAngle - endAngle) / (textString.length - 1);
let angle = startAngle;
let index = 0;
let character: string;
while (index < textString.length) {
character = textString.charAt(index);
this.canvasContext?.save();
this.canvasContext?.beginPath();
this.canvasContext?.translate(circleText.x + Math.cos(angle) * radius,
circleText.y - Math.sin(angle) * radius);
this.canvasContext?.rotate(Math.PI / CommonConstants.TWO - angle);
this.canvasContext?.fillText(character, 0, 0);
angle -= angleDecrement;
index++;
this.canvasContext?.restore();
}
}
畫(huà)內(nèi)部抽獎(jiǎng)區(qū)域文字對(duì)應(yīng)圖片:使用drawImage()方法繪制抽獎(jiǎng)區(qū)域文字對(duì)應(yīng)圖片,該方法接收五個(gè)參數(shù),分別是圖片資源、繪制區(qū)域左上角的X和Y軸坐標(biāo)、繪制區(qū)域的寬度和高度。
// DrawModel.ets
// 畫(huà)內(nèi)部扇形區(qū)域文字對(duì)應(yīng)的圖片
drawImage() {
let beginAngle = this.startAngle;
let imageSrc = [
CommonConstants.WATERMELON_IMAGE_URL, CommonConstants.BEER_IMAGE_URL,
CommonConstants.SMILE_IMAGE_URL, CommonConstants.CAKE_IMAGE_URL,
CommonConstants.HAMBURG_IMAGE_URL, CommonConstants.SMILE_IMAGE_URL
];
for (let i = 0; i < CommonConstants.COUNT; i++) {
let image = new ImageBitmap(imageSrc[i]);
this.canvasContext?.save();
this.canvasContext?.rotate(beginAngle * Math.PI / CommonConstants.HALF_CIRCLE);
this.canvasContext?.drawImage(image, this.screenWidth * CommonConstants.IMAGE_DX_RATIOS,
this.screenWidth * CommonConstants.IMAGE_DY_RATIOS, CommonConstants.IMAGE_SIZE,
CommonConstants.IMAGE_SIZE);
beginAngle += this.avgAngle;
this.canvasContext?.restore();
}
}
實(shí)現(xiàn)抽獎(jiǎng)功能
在CanvasPage.ets的Canvas組件中添加rotate屬性,在Image組件中添加點(diǎn)擊事件onClick。點(diǎn)擊“開(kāi)始抽獎(jiǎng)”圖片,圓形轉(zhuǎn)盤(pán)開(kāi)始轉(zhuǎn)動(dòng)抽獎(jiǎng)。
// CanvasPage.ets
Stack({ alignContent: Alignment.Center }) {
Canvas(this.canvasContext)
...
.onReady(() = > {
this.drawModel.draw(this.canvasContext, this.screenWidth, this.screenHeight);
})
.rotate({
x: 0,
y: 0,
z: 1,
angle: this.rotateDegree,
centerX: this.screenWidth / CommonConstants.TWO,
centerY: this.screenHeight / CommonConstants.TWO
})
// 開(kāi)始抽獎(jiǎng)圖片
Image($r('app.media.ic_center'))
...
.enabled(this.enableFlag)
.onClick(() = > {
this.enableFlag = !this.enableFlag;
// 開(kāi)始抽獎(jiǎng)
this.startAnimator();
})
}
...
圓形轉(zhuǎn)盤(pán)開(kāi)始轉(zhuǎn)動(dòng)抽獎(jiǎng):給轉(zhuǎn)盤(pán)指定一個(gè)隨機(jī)的轉(zhuǎn)動(dòng)角度randomAngle,保證每次轉(zhuǎn)動(dòng)的角度是隨機(jī)的,即每次抽到的獎(jiǎng)品也是隨機(jī)的。動(dòng)畫(huà)結(jié)束后,轉(zhuǎn)盤(pán)停止轉(zhuǎn)動(dòng),抽獎(jiǎng)結(jié)束,彈出抽中的獎(jiǎng)品信息。
// CanvasPage.ets
dialogController: CustomDialogController = new CustomDialogController({
builder: PrizeDialog({
prizeData: $prizeData,
enableFlag: $enableFlag
}),
autoCancel: false
});
// CanvasPage.ets
// 開(kāi)始抽獎(jiǎng)
startAnimator() {
let randomAngle = Math.round(Math.random() * CommonConstants.CIRCLE);
// 獲取中獎(jiǎng)信息
this.prizeData = this.drawModel.showPrizeData(randomAngle);
animateTo({
duration: CommonConstants.DURATION,
curve: Curve.Ease,
delay: 0,
iterations: 1,
playMode: PlayMode.Normal,
onFinish: () = > {
this.rotateDegree = CommonConstants.ANGLE - randomAngle;
// 打開(kāi)自定義彈窗,彈出抽獎(jiǎng)信息
this.dialogController.open();
}
}, () = > {
this.rotateDegree = CommonConstants.CIRCLE * CommonConstants.FIVE +
CommonConstants.ANGLE - randomAngle;
})
}
彈出抽中的獎(jiǎng)品信息:抽獎(jiǎng)結(jié)束后,彈出抽中的文本和圖片信息,通過(guò)自定義彈窗實(shí)現(xiàn)。
// PrizeDialog.ets
@CustomDialog
export default struct PrizeDialog {
@Link prizeData: PrizeData;
@Link enableFlag: boolean;
private controller?: CustomDialogController;
build() {
Column() {
Image(this.prizeData.imageSrc)
...
Text(this.prizeData.message)
...
Text($r('app.string.text_confirm'))
...
.onClick(() = > {
// 關(guān)閉自定義彈窗
this.controller?.close();
this.enableFlag = !this.enableFlag;
})
}
...
}
}
審核編輯 黃宇
-
開(kāi)發(fā)板
+關(guān)注
關(guān)注
25文章
6112瀏覽量
112914 -
鴻蒙
+關(guān)注
關(guān)注
60文章
2839瀏覽量
45334 -
HarmonyOS
+關(guān)注
關(guān)注
80文章
2146瀏覽量
35511
發(fā)布評(píng)論請(qǐng)先 登錄
HarmonyOS開(kāi)發(fā)案例:【W(wǎng)eb組件實(shí)現(xiàn)抽獎(jiǎng)】
HarmonyOS5云服務(wù)技術(shù)分享--Serverless抽獎(jiǎng)模板部署
Deyisupport 社區(qū) 6 周年慶 —— 三重活動(dòng) + 幸運(yùn)大轉(zhuǎn)盤(pán)抽獎(jiǎng)
HarmonyOS IoT 硬件開(kāi)發(fā)案例分享
【潤(rùn)和直播課預(yù)告@華為開(kāi)發(fā)者學(xué)院】HarmonyOS設(shè)備開(kāi)發(fā)基礎(chǔ)課程|HiSpark WiFi-IoT 智能小車(chē)套件開(kāi)發(fā)案例
6月2日!華為HarmonyOS2.0發(fā)布會(huì)直播間抽獎(jiǎng)公示&領(lǐng)獎(jiǎng)方式
通過(guò)一個(gè)圓形抽獎(jiǎng)轉(zhuǎn)盤(pán)演示HarmonyOS自定義組件的實(shí)現(xiàn)
聲光電子轉(zhuǎn)盤(pán)聲光電子轉(zhuǎn)盤(pán)的電路原理圖
許思維老師HarmonyOS IoT硬件開(kāi)發(fā)案例分享
華為開(kāi)發(fā)者分論壇HarmonyOS學(xué)生公開(kāi)課-OpenHarmony Codelabs開(kāi)發(fā)案例
基于SpringBoot+Redis的轉(zhuǎn)盤(pán)抽獎(jiǎng)
HarmonyOS開(kāi)發(fā)案例:【抽獎(jiǎng)轉(zhuǎn)盤(pán)】

HarmonyOS開(kāi)發(fā)案例:【抽獎(jiǎng)轉(zhuǎn)盤(pán)】
評(píng)論