九宫格 NinePatch

      我们经常会遇到一些尺寸不固定,但是周围或四遍样式不变形的图片,也就是 .9 图,例如消息气泡,如果直接设置宽高会将整个气泡图片拉变形。 下图中,第二个是通过九宫格创建的气泡,最后一个是直接把图片拉伸创建的,前两个明显符合预期。Demo

      image.png

      安装

      使用 NPM

      1. npm i @eva/plugin-renderer @eva/plugin-renderer-nine-patch

      在浏览器中

      1. <script src=https://unpkg.com/@eva/plugin-renderer-nine-patch@1.2.x/dist/EVA.plugin.renderer.ninePatch.min.js></script>

      使用

      1. import { Game, GameObject, resource, RESOURCE_TYPE } from ‘@eva/eva.js’
      2. import { RendererSystem } from ‘@eva/plugin-renderer’
      3. import { NinePatch, NinePatchSystem } from ‘@eva/plugin-renderer-nine-patch’
      4. resource.addResource([
      5. {
      6. name: ‘nine’,
      7. type: RESOURCE_TYPE.IMAGE,
      8. src: {
      9. image: {
      10. type: ‘png’,
      11. url: https://img.alicdn.com/tfs/TB17uSKkQ9l0K4jSZFKXXXFjpXa-363-144.png
      12. }
      13. },
      14. preload: false
      15. }
      16. ])
      17. const game = new Game({
      18. systems: [
      19. new RendererSystem({
      20. canvas: document.querySelector(‘#canvas’),
      21. width: 750,
      22. height: 1000,
      23. backgroundColor: 0xffffff
      24. }),
      25. new NinePatchSystem()
      26. ]
      27. })
      28. const patch = new GameObject(‘patch’, {
      29. size: { width: 360, height: 145 },
      30. origin: { x: 0, y: 0 },
      31. position: {
      32. x: 10,
      33. y: 10
      34. },
      35. anchor: {
      36. x: 0,
      37. y: 0
      38. }
      39. })
      40. const ninePatch = patch.addComponent(
      41. new NinePatch({
      42. resource: ‘nine’,
      43. leftWidth: 100,
      44. topHeight: 40,
      45. rightWidth: 40,
      46. bottomHeight: 40
      47. })
      48. )
      49. const patch1 = new GameObject(‘patch1’, {
      50. size: { width: 660, height: 345 },
      51. origin: { x: 0, y: 0 },
      52. position: {
      53. x: 10,
      54. y: 300
      55. },
      56. anchor: {
      57. x: 0,
      58. y: 0
      59. }
      60. })
      61. const ninePatch1 = patch1.addComponent(
      62. new NinePatch({
      63. resource: ‘nine’,
      64. leftWidth: 100,
      65. topHeight: 40,
      66. rightWidth: 40,
      67. bottomHeight: 40
      68. })
      69. )
      70. game.scene.addChild(patch)
      71. game.scene.addChild(patch1)

      参数

      resource string

      资源名称

      spriteName

      如果资源类型是 Sprite 可设置此属性

      leftWidth

      对应下图 A

      topHeight

      对应下图 C

      rightWidth

      对应下图 B

      bottomHeight

      对应下图 D

      image.png

      ,