Creating & Using 9-patch images in Android

前端 未结 8 2119
走了就别回头了
走了就别回头了 2020-11-30 00:39

I recently heard about 9-patch images. I know its 9 tiled and is stretchable. I\'d like to know more about it.

  • How can I create a 9-patch image?

    Is th

8条回答
  •  臣服心动
    2020-11-30 01:08

    The SDK and Android Studio both ship with the "Draw 9-patch" tool ("draw9patch" in the SDK tools folder) which is a simple editor. Here is a nicer one which is also open source. It has a simple but clever default image.

    The official documentation has improved over the years. In summary, nine patch images' most important advantage is that they can specify (non-contiguous) areas to scale:

    A NinePatch graphic is a standard PNG image that includes an extra 1-pixel border. It must be saved with the 9.png extension in the res/drawable/ directory of your project.

    Use the border to define the stretchable and static areas of the image. You indicate a stretchable section by drawing one (or more) 1-pixel wide black line(s) in the left and top part of the border (the other border pixels should be fully transparent or white). You can have as many stretchable sections as you want. The relative size of the stretchable sections stays the same, so the largest section always remains the largest.

    You can also define an optional drawable section of the image (effectively, the padding lines) by drawing a line on the right and a line on the bottom. If a View object sets the NinePatch graphic as its background and then specifies the view's text, it stretches itself so that all the text occupies only the area designated by the right and bottom lines (if included). If the padding lines aren't included, Android uses the left and top lines to define this drawable area.

    But the docs lack good examples. This tutorial has some great examples at the end that answer the second part of your question, explaining how the scaling works - not just for buttons - but also frames, and it has a complete example project that you can download and play with.

提交回复
热议问题