问题 :安卓加载网络.9图 不会自适应
解决方案:需要先将.9图处理成正常的使用格式
我们使用Android SDK的build-tools下到工具来处理,打开命令行来处理吧,如下:
1、点9图转换:找到转化工具路径(这个路径是我本人的电脑SDK安装路径)
D:\android_sdk\build-tools\33.0.1> (打开命令行)
//单张图片转换,命令:aapt s -i 点9图路径 -o 转换后的图片输出路径
aapt s -i E:\res\shengdan.9.png -o E:\res\shengdan2.png
//图片文件的批量转换,命令:aapt c -v -S 文件夹路径 -C 转换后的图片文件夹的输出路径
aapt c -v -S E:\res -C E:\res\9out
转化后的点9图 ,上传到服务器然后我们进行正常加载了
下面是需要用到的LoadDian9TuUtil 代码
public static void loadDian9Tu(Context context, View imageView, String imgUrl) {
if (context == null) {
return;
}
if (context instanceof Activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (((Activity) context).isDestroyed()) {
return;
}
}
}
Glide.with(context)
.asFile()
.load(imgUrl)
.into(new CustomTarget<File>() {
@Override
public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
try {
FileInputStream is = new FileInputStream(resource);
setNinePathImage(context, imageView, BitmapFactory.decodeStream(is));
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}
public static void setNinePathImage(Context context, View imageView, Bitmap bitmap) {
if (bitmap == null)
return;
byte[] chunk = bitmap.getNinePatchChunk();
if (NinePatch.isNinePatchChunk(chunk)) {
NinePatchDrawable patchy = new NinePatchDrawable(context.getResources(), bitmap, chunk, NinePatchChunk.deserialize(chunk).mPaddings, null);
imageView.setBackground(patchy);
}
}
NinePatchChunk 处理类
public static final int NO_COLOR = 0x00000001;
public static final int TRANSPARENT_COLOR = 0x00000000;
public final Rect mPaddings = new Rect();
public int mDivX[];
public int mDivY[];
public int mColor[];
private static void readIntArray(final int[] data, final ByteBuffer buffer) {
for (int i = 0, n = data.length; i < n; ++i)
data[i] = buffer.getInt();
}
private static void checkDivCount(final int length) {
if (length == 0 || (length & 0x01) != 0)
throw new RuntimeException("invalid nine-patch: " + length);
}
public static NinePatchChunk deserialize(final byte[] data) {
final ByteBuffer byteBuffer =
ByteBuffer.wrap(data).order(ByteOrder.nativeOrder());
if (byteBuffer.get() == 0) return null; // is not serialized
final NinePatchChunk chunk = new NinePatchChunk();
chunk.mDivX = new int[byteBuffer.get()];
chunk.mDivY = new int[byteBuffer.get()];
chunk.mColor = new int[byteBuffer.get()];
checkDivCount(chunk.mDivX.length);
checkDivCount(chunk.mDivY.length);
// skip 8 bytes
byteBuffer.getInt();
byteBuffer.getInt();
chunk.mPaddings.left = byteBuffer.getInt();
chunk.mPaddings.right = byteBuffer.getInt();
chunk.mPaddings.top = byteBuffer.getInt();
chunk.mPaddings.bottom = byteBuffer.getInt();
// skip 4 bytes
byteBuffer.getInt();
readIntArray(chunk.mDivX, byteBuffer);
readIntArray(chunk.mDivY, byteBuffer);
readIntArray(chunk.mColor, byteBuffer);
return chunk;
}
保存记录,方便以后直接使用