九宫格精灵
¥NineSlice Sprite
NineSliceSprite
是 Sprite
的一种特殊类型,允许在保留角和边的同时调整纹理大小。它对于构建可扩展的 UI 元素(例如按钮、面板或带有圆角或装饰边框的窗口)特别有用。
¥NineSliceSprite
is a specialized type of Sprite
that allows textures to be resized while preserving the corners and edges. It is particularly useful for building scalable UI elements like buttons, panels, or windows with rounded or decorated borders.
import { NineSliceSprite, Texture } from 'pixi.js';
const nineSlice = new NineSliceSprite({
texture: Texture.from('button.png'),
leftWidth: 15,
topHeight: 15,
rightWidth: 15,
bottomHeight: 15,
width: 200,
height: 80,
});
app.stage.addChild(nineSlice);
你也可以只传递一个纹理,切片值将恢复为默认值或从纹理的 defaultBorders
推断出来。
¥You can also pass just a texture, and the slice values will fall back to defaults or be inferred from the texture’s defaultBorders
.
NineSlice 的工作原理
¥How NineSlice Works
九切片纹理的划分方式如下:
¥Here’s how a nine-slice texture is divided:
A B
+---+----------------------+---+
C | 1 | 2 | 3 |
+---+----------------------+---+
| | | |
| 4 | 5 | 6 |
| | | |
+---+----------------------+---+
D | 7 | 8 | 9 |
+---+----------------------+---+
Areas:
- 1, 3, 7, 9: Corners (remain unscaled)
- 2, 8: Top/Bottom center (stretched horizontally)
- 4, 6: Left/Right center (stretched vertically)
- 5: Center (stretched in both directions)
这可确保保留装饰角,并且中心内容可以根据需要缩放。
¥This ensures that decorative corners are preserved and the center content can scale as needed.
宽度和高度行为
¥Width and Height Behavior
在 NineSliceSprite
上设置 .width
和 .height
会更新几何顶点,而不是纹理 UV。这允许纹理根据切片区域正确重复或拉伸。这也意味着 width
和 height
属性与 scale
属性不同。
¥Setting .width
and .height
on a NineSliceSprite
updates the geometry vertices, not the texture UVs. This allows the texture to repeat or stretch correctly based on the slice regions. This also means that the width
and height
properties are not the same as the scale
properties.
// The texture will stretch to fit the new dimensions
nineSlice.width = 300;
nineSlice.height = 100;
// The nine-slice will increase in size uniformly
nineSlice.scale.set(2); // Doubles the size
原始宽度和高度
¥Original Width and Height
如果你需要知道九宫格的原始大小,可以通过 originalWidth
和 originalHeight
属性访问。这些值在创建 NineSliceSprite
时设置,表示在应用任何缩放或调整大小之前纹理的尺寸。
¥If you need to know the original size of the nine-slice, you can access it through the originalWidth
and originalHeight
properties. These values are set when the NineSliceSprite
is created and represent the dimensions of the texture before any scaling or resizing is applied.
console.log(nineSlice.originalWidth);
console.log(nineSlice.originalHeight);
动态更新
¥Dynamic Updates
你可以在运行时更改切片尺寸或大小:
¥You can change slice dimensions or size at runtime:
nineSlice.leftWidth = 20;
nineSlice.topHeight = 25;
每个 setter 都会触发几何更新以反映更改。
¥Each setter triggers a geometry update to reflect the changes.
API 参考
¥API Reference