# NinePictureDemo **Repository Path**: maxinDev/nine-picture-demo ## Basic Information - **Project Name**: NinePictureDemo - **Description**: Android中动态加载.9图的Demo - **Primary Language**: Android - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-04-22 - **Last Updated**: 2022-05-25 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # NinePictureDemo #### 介绍 Android中动态加载.9图的Demo 1. 将`.9图`使用sdk目录下的aapt工具将`.9图`转换为`png图`(打包APK的时候会自动转换) 2. 图片加载到`Bitmap`,使用`NinePatch.isNinePatchChunk(bitmap.getNinePatchChunk())`判断是否是`.9图` 3. 创建`.9图`对象,使用api `new NinePatchDrawable(Resources res, Bitmap bitmap, byte[] chunk, Rect padding, Rect opticalInsets, String srcName)` 4. `NinePatchDrawable`加载到view中 ![demo截图](https://images.gitee.com/uploads/images/2021/0422/165727_b589d87c_1518014.gif "ninepatch.gif") ```kotlin val inputStream = targetView.context.resources.assets.open(path) val bitmap = BitmapFactory.decodeStream(inputStream) if(isUseNinePatch){ val chunk = bitmap.ninePatchChunk if(NinePatch.isNinePatchChunk(chunk)){ val drawable = NinePatchDrawable(targetView.resources, bitmap, chunk, NinePatchChunk.getPaddingRect(chunk), "") targetView.background = drawable }else{ Toast.makeText(targetView.context, "只能加载.9背景图", Toast.LENGTH_SHORT).show() } }else{ targetView.background = bitmap.toDrawable(targetView.resources) } ```