卡片使用自定义绘制能力

2024-01-25 12:20 更新

卡片使用自定义绘制能力

更新时间: 2024-01-24 14:34
分享
添加收藏
ArkTS卡片开放了自定义绘制的能力,在卡片上可以通过Canvas组件创建一块画布,然后通过CanvasRenderingContext2D对象在画布上进行自定义图形的绘制,如下示例代码实现了在画布的中心绘制了一个笑脸。
  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回调中获取画布的实际宽和高
  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. // 在画布的中心绘制一个红色的圆
  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. }

运行效果如下图所示。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号