Skip to content

Nine-slice

A panel drawn as an image looks wrong when it is stretched: its rounded corners and its border stretch with it. Nine-slice cuts the frame into nine pieces with four insets: the corners keep their size, the edges stretch along their length, and the middle fills the rest. Set the sprite’s width and height to anything, every frame if you like.

┌────┬──────────┬────┐
│ TL │ top │ TR │ corners: never stretched
├────┼──────────┼────┤
│left│ middle │rght│ edges: stretched along their length
├────┼──────────┼────┤ middle: stretched both ways
│ BL │ bottom │ BR │
└────┴──────────┴────┘
await engine.load({ ui: 'art/ui.json' })
const panel = stage.add(engine.sprite('ui/panel', { slice: 24, x: 40, y: 40, width: 420, height: 160 }))
const button = stage.add(engine.sprite('ui/button', { slice: [12, 30, 12, 30], width: 260, height: 72 }))

slice works on any sprite, from a loaded image or a frame of a loaded atlas:

  • one number for the same inset on every side, or [top, right, bottom, left] (CSS order);
  • in the frame’s pixels, measured on the image as you drew it;
  • 0 (the default): no slicing, or the frame’s own insets if its atlas gives them (below).

Change sprite.slice at any time. Insets bigger than the sprite shrink in proportion, so a panel resized to almost nothing still looks like a small panel. Drawing a nine-sliced sprite allocates nothing, so a progress bar can change its width every frame.

The engine’s own roundRect shapes are nine-sliced by themselves: for a plain rounded panel you need no image at all.

A frame of an atlas’s JSON (hash or array) may carry its nine-slice borders as scale9Borders: { x, y, w, h }: Phaser’s name for the middle rectangle, in the untrimmed frame’s pixels. engine.load reads them: sprites of that frame are nine-sliced by default, with no slice in the code. A slice on the sprite still wins.

(The engine reads atlases with a top-level frames, TexturePacker’s “JSON (Hash)” and “JSON (Array)”. Add scale9Borders to such a file, or export from a tool that writes it there.)

Texture packers usually trim frames: they cut away the transparent border and remember where the frame sat (trimmed, spriteSourceSize, sourceSize in the JSON). The engine reads that: a trimmed frame is drawn at its untrimmed size, with its picture where it was.

With nine-slice, give the insets of the untrimmed frame, as you drew it. The transparent edges that were trimmed stay in the corners and are never stretched; the rest of each inset slices the trimmed picture.

A frame you bake is drawn at the backing store’s resolution (engine.pixelScale pixels per stage unit), and its pixels change with the screen and the tier. Insets in its pixels would change with them, so don’t nine-slice baked frames: use a roundRect shape for a rounded panel, or load the panel as an image.