动态设置9patch背景

Too*_*hka 4 android background button nine-patch

有没有人试图动态设置9Patch背景的按钮?如果重要,则按钮的宽度和高度设置为wrap_content

如果是的话,你是如何解决"黑线"问题的?

谢谢

brn*_*nes 5

如果你看到你在9补丁图像上绘制的黑点,那是因为你还没有预编译你的图像.

要在运行时将9补丁图像设置为背景,必须先将它们编译,然后删除边框并将其编码为PNG块.

您可以通过在res/drawable应用程序的文件夹中插入.9.png图像,编译它并生成.apk(在Eclipse上,右键单击您的project root > Android Tools > Export Unsigned Application Package)来实现.然后解压缩.apk,你将获得带有9补丁编译数据的.9.png图像.

使用预编译的9补丁图像,执行类似的操作来加载图像:

private Drawable loadNinePatch(String path, Context context) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        byte[] chunk = bitmap.getNinePatchChunk();
        if(NinePatch.isNinePatchChunk(chunk)) {
            return new NinePatchDrawable(context.getResources(), bitmap, chunk, new Rect(), null);
        } else return new BitmapDrawable(bitmap);
}
Run Code Online (Sandbox Code Playgroud)

然后将其设置为按钮的背景:

button.setBackgroundDrawable(loadNinePatch("/data/data/your.app/files/button_background.9.png", context));
Run Code Online (Sandbox Code Playgroud)