Android 加载服务器的.9图片

2019-12-11  本文已影响0人  RookieRun

1.9-patch图片的制作: 点我直接上车

2.9-patch上传服务器(尤为重要的一步)

1.上传服务器时,不能将步骤1中制作的.9图直接上传服务器,而是需要转换为png后在上传,原因:

getNinePatchChunk works just fine. It returned null 
because you were giving Bitmap a “source” ninepatch. 
It needs a “compiled” ninepatch image.

There are two types of ninepatch file formats in the Android world (“source” and “compiled”).

 The source version is where you add the 1px transparency border everywhere–
 when you compile your app into a .apk later, 
aapt will convert your *.9.png files to the binary format that Android expects. 
This is where the png file gets its “chunk” metadata

2.转换的方法
2.1直接搞一个demo工程,将.9图片放进去编程apk后,再解压拿到对应的.9图
2.2使用build-tools文件夹中的aapt命令

aapt s -i test.9.png -o test.png
Crunching single PNG file: test.9.png
    Output file: test.png

3.9-patch图片下载

4.9-patch图片的转换及设置

拿到网络图片的bitmap(BitmapFactory.decodeStream,decodeByteArray...)
  Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                if (bitmap != null) {
                    byte[] ninePatchChunk = bitmap.getNinePatchChunk();
                    boolean isNinePatch = NinePatch.isNinePatchChunk(ninePatchChunk);
                    if (isNinePatch) {
                        final NinePatchDrawable ninePatchDrawable = new NinePatchDrawable(bitmap, ninePatchChunk, new Rect(), null);
                        PersonalMoreActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ((ImageView) findViewById(R.id.iv_test)).setImageDrawable(ninePatchDrawable);
                                textView.setBackground(ninePatchDrawable);
                            }
                        });
                    }
                }

参考文章:
1.create-a-ninepatch-ninepatchdrawable-in-runtime

上一篇下一篇

猜你喜欢

热点阅读