RoundRectMask.ts 2.6 KB

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