SelfMask.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { _decorator, Component, game, Graphics, Mask, Node, UITransform } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('SelfMask')
  4. export class SelfMask extends Component {
  5. @property()
  6. private _radius: number = 50;
  7. @property({ tooltip: "圆角半径:\n0-1之间为最小边长比例值, \n>1为具体像素值" })
  8. public get radius(): number {
  9. return this._radius;
  10. }
  11. // public radius: number = 50;
  12. public set radius(r: number) {
  13. this._radius = r;
  14. this.updateMask(r);
  15. }
  16. // @property(cc.Mask)
  17. protected mask: Mask = null;
  18. protected onEnable(): void {
  19. this.mask = this.getComponent(Mask);
  20. this.updateMask(this.radius);
  21. }
  22. private updateMask(r: number) {
  23. let _radius = r >= 0 ? r : 0;
  24. if (_radius < 1) {
  25. _radius = Math.min(this.node.getComponent(UITransform).width, this.node.getComponent(UITransform).height) * _radius;
  26. }
  27. this.mask["radius"] = _radius;
  28. this.mask["onDraw"] = this.onDraw.bind(this.mask);
  29. this.mask["_updateGraphics"] = this._updateGraphics.bind(this.mask);
  30. this.mask.type = Mask.Type.GRAPHICS_STENCIL;
  31. }
  32. private _updateGraphics() {
  33. // @ts-ignore.
  34. let graphics = this._graphics;
  35. if (!graphics) {
  36. return;
  37. }
  38. this.onDraw(graphics);
  39. }
  40. /**
  41. * mask 用于绘制罩子的函数.
  42. * this 指向mask 对象,需要特别注意.
  43. * @param graphics
  44. */
  45. protected onDraw(graphics: Graphics) {
  46. // Share render data with graphics content
  47. graphics.clear();
  48. let node = this.node;
  49. let width = node.getComponent(UITransform).width;
  50. let height = node.getComponent(UITransform).height;
  51. let x = -width * node.getComponent(UITransform).anchorX;
  52. let y = -height * node.getComponent(UITransform).anchorY;
  53. graphics.roundRect(x, y, width, height, this.radius || 0);
  54. graphics.stroke();
  55. graphics.fill();
  56. }
  57. }