Scale a sprite using nine-part algorithm.
The size of the sprite node’s
frame property is determined by the values of these properties:
The sprite node’s
sizeproperty holds its base (unscaled) size. When a sprite is initialized using
init(image, the value of this property is initialized to be equal to the size of the supplied image.
When a sprite node’s frame is larger than its texture, the texture is stretched to cover its frame. Normally, the texture is stretched uniformly across the frame, as shown in the following figure.
However, sometimes you want to use sprite nodes to build user interface elements, such as buttons or health indicators. Often, these elements contain fixed-size elements, such as end caps, that should not be stretched. In this case, use a portion of the texture without stretching, and then stretch the remaining part of the texture over the rest of the frame.
center property, which is specified in unit coordinates of the texture, controls the scaling behavior. The default value is a rectangle that covers the entire texture, which is why the entire texture is stretched across the frame. If you specify a rectangle that only covers a portion of the texture, you create a 3 x 3 grid. Each box in the grid has its own scaling behavior:
The portions of the texture in the four corners of the grid are drawn without any scaling.
The center of the grid is scaled in both dimensions.
The upper- and lower-middle parts are only scaled horizontally.
The left- and right-middle parts are only scaled vertically.
The following figure shows a close-up view of a texture you might use to draw a user interface button. The complete texture is 28 x 28 pixels. The corner pieces are each 12 x 12 pixels and the center is 4 x 4 pixels.
The following code shows how this button sprite would be initialized. The
center property is computed based on the design of the texture.
The following figure shows that the corners remain the same, even when the button is drawn at different sizes.