本文参考 juejin.cn/post/684490… 记录一下.9图的使用,自己总结下,附Demo
常用操作
- 制作好
.9图
打包到APK中直接使用(基本操作) - 动态加载本地、服务器的
.9图
- 使用代码动态创建
.9图
加载.9图流程
.9图
是在原图基础上,上下左右方向各加了1px
,同时通过使用黑线(#FF000000)标记,规定图片的拉伸以及内容区域的填充。
左-黑点 纵向拉伸区域
上-黑点 横向拉伸区域
右-黑线 纵向显示区域
下-黑线 横向显示区域
要在Android中加载.9图
- 制作好
.9图
- 将
.9图
使用sdk目录下的aapt工具将.9图
转换为png图
(打包APK的时候会自动转换) - 图片加载到
Bitmap
,使用NinePatch.isNinePatchChunk(bitmap.getNinePatchChunk())
判断是否是.9图
- 创建
.9图
对象,使用apinew NinePatchDrawable(Resources res, Bitmap bitmap, byte[] chunk, Rect padding, Rect opticalInsets, String srcName)
NinePatchDrawable
加载到view中
核心代码
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);
}
}
}
复制代码
示例Demo:demo地址
aapt转换.9图
单文件转换: ./aapt s -i xxx.9.png -o xxx.png
批量转换 ./aapt c -S inputDir -C outputDir
其中 inputDir 为原始.9图文件夹,outputDir 为输出文件夹
aapt在sdk目录的build-tools文件夹下,如:**\sdk\build-tools\29.0.2
示例:
#单文件转换
D:\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
#批量转换
D:\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
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END