卡片使用自定義繪制能力

2024-01-25 12:20 更新

卡片使用自定義繪制能力

更新時(shí)間: 2024-01-24 14:34
分享
添加收藏
ArkTS卡片開放了自定義繪制的能力,在卡片上可以通過Canvas組件創(chuàng)建一塊畫布,然后通過CanvasRenderingContext2D對(duì)象在畫布上進(jìn)行自定義圖形的繪制,如下示例代碼實(shí)現(xiàn)了在畫布的中心繪制了一個(gè)笑臉。
  1. @Entry
  2. @Component
  3. struct Card {
  4. private canvasWidth: number = 0;
  5. private canvasHeight: number = 0;
  6. // 初始化CanvasRenderingContext2D和RenderingContextSettings
  7. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  8. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  9. build() {
  10. Column() {
  11. Row() {
  12. Canvas(this.context)
  13. .margin('5%')
  14. .width('90%')
  15. .height('90%')
  16. .onReady(() => {
  17. console.info('[ArkTSCard] onReady for canvas draw content');
  18. // 在onReady回調(diào)中獲取畫布的實(shí)際寬和高
  19. this.canvasWidth = this.context.width;
  20. this.canvasHeight = this.context.height;
  21. // 繪制畫布的背景
  22. this.context.fillStyle = 'rgba(203, 154, 126, 1.00)';
  23. this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
  24. // 在畫布的中心繪制一個(gè)紅色的圓
  25. this.context.beginPath();
  26. let radius = this.context.width / 3
  27. let circleX = this.context.width / 2
  28. let circleY = this.context.height / 2
  29. this.context.moveTo(circleX - radius, circleY);
  30. this.context.arc(circleX, circleY, radius, 2 * Math.PI, 0, true);
  31. this.context.closePath();
  32. this.context.fillStyle = 'red';
  33. this.context.fill();
  34. // 繪制笑臉的左眼
  35. let leftR = radius / 4
  36. let leftX = circleX - (radius / 2)
  37. let leftY = circleY - (radius / 3.5)
  38. this.context.beginPath();
  39. this.context.arc(leftX, leftY, leftR, 0, Math.PI, true);
  40. this.context.strokeStyle = '#ffff00'
  41. this.context.lineWidth = 10
  42. this.context.stroke()
  43. // 繪制笑臉的右眼
  44. let rightR = radius / 4
  45. let rightX = circleX + (radius / 2)
  46. let rightY = circleY - (radius / 3.5)
  47. this.context.beginPath();
  48. this.context.arc(rightX, rightY, rightR, 0, Math.PI, true);
  49. this.context.strokeStyle = '#ffff00'
  50. this.context.lineWidth = 10
  51. this.context.stroke()
  52. // 繪制笑臉的嘴巴
  53. let mouthR = radius / 2.5
  54. let mouthX = circleX
  55. let mouthY = circleY + (radius / 3)
  56. this.context.beginPath();
  57. this.context.arc(mouthX, mouthY, mouthR, Math.PI, 0, true);
  58. this.context.strokeStyle = '#ffff00'
  59. this.context.lineWidth = 10
  60. this.context.stroke()
  61. })
  62. }
  63. }.height('100%').width('100%')
  64. }
  65. }

運(yùn)行效果如下圖所示。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)