Nanfeng

Notes on software development, code, and curious ideas

Creating a Circular Mask in Cocos Creator

You can display a square image as a circle by creating a custom circular mask in Cocos Creator.

  1. Create a Canvas and add a Sprite containing the image.
  2. Add a node under the Canvas and name it Mask.
  3. Set the Mask node’s content size to the same dimensions as the image.
  4. Add a Graphics component to the Mask node.
  5. Attach the following TypeScript component to the Mask node:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { _decorator, Component, color, Graphics, UITransform } from 'cc';

const { ccclass, property } = _decorator;

@ccclass('MaskCircle')
export class MaskCircle extends Component {
@property(Graphics)
maskGraphics: Graphics = null!;

start() {
this.drawCircleMask();
}

drawCircleMask() {
const graphics: Graphics = this.maskGraphics;
graphics.clear();
graphics.fillColor = color(255, 255, 255, 255);
graphics.circle(
0,
0,
this.node.getComponent(UITransform).width / 2
);
graphics.fill();
}
}
  1. In the Inspector, connect the maskGraphics property of MaskCircle to the node’s Graphics component.
  2. Position the Mask node over the image and make the image node a child of the Mask node so that the mask affects it.
  3. Run the scene. The image should now appear circular.

Adjust the Mask node’s dimensions to match the source image, and customize the shape as needed.

+