Reference for this article is juejin.cn/post/684490… Record.9 figure use, their summary, attached Demo
Common operations
- It is made ready
9 figure.
Package into APK for direct use (basic operation) - Dynamically load local, server
9 figure.
- Dynamically created using code
9 figure.
Load.9 Figure flow
On the basis of the original image, 1px was added in the upper, lower, left and right directions, and black line (#FF000000) was used to define the stretching of the image and the filling of the content area.
Left-black dot vertical stretching area up-black dot horizontal stretching area right-black line vertical display area down-black line horizontal display area
To load the.9 diagram in Android
- It is made ready
9 figure.
- will
9 figure.
Use the AAPT tool in the SDK directory9 figure.
convertPNG figure
(Automatic conversion when packaging APK) - Image loading to
Bitmap
, the use ofNinePatch.isNinePatchChunk(bitmap.getNinePatchChunk())
Determine whether or not9 figure.
- create
9 figure.
Object, using the APInew NinePatchDrawable(Resources res, Bitmap bitmap, byte[] chunk, Rect padding, Rect opticalInsets, String srcName)
NinePatchDrawable
Load it into the View
The core code
public static void setNineImagePatch(View view, File file, String url) {
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
byte[] chunk = bitmap.getNinePatchChunk();
if (NinePatch.isNinePatchChunk(chunk)) {
NinePatchDrawable patchy = new NinePatchDrawable(view.getResources(), bitmap, chunk, new Rect(), null); view.setBackground(patchy); }}}Copy the code
Example Demo: Demo address
Aapt conversion.9 figure
Single file conversion:./aapt s -i xxx.9.png -o xxx.png
/aapt c -s inputDir -c outputDir inputDir is the original.9 Figure folder, outputDir is the output folder
Aapt is in the build-tools folder of the SDK directory, such as: **\ SDK \build-tools\29.0.2 Example:
Single file conversionD:\tools\sdk\build-tools\ 29.0.3 >aapt s -i d: /temp/ 1.9.png -o d: /temp/out/ 1.png
Crunching single PNG file: d: \temp\ 1.9.png
Output file: d: \temp\out\ 1.png# Batch conversionD: \tools\sdk\build-tools\ 29.0.3 >aapt c -S d: /temp/in -C d: /temp/out
Crunching PNG Files in source dir: d: \temp\in
To destination dir: d: \temp\out
Copy the code