gpt4 book ai didi

android - 如何通过代码将xml层列表转换为layerdrawable

转载 作者:搜寻专家 更新时间:2023-11-01 08:13:44 25 4
gpt4 key购买 nike

我正在尝试通过代码对以下 xml 进行编码。

----drawable\my_layerdrawable.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<bitmap android:src="@drawable/my_image"
android:gravity="left"/>
</item>
<item android:left="10dp">
<bitmap android:src="@drawable/my_image"
android:gravity="left" />
</item>
<item android:top="10dp">
<bitmap android:src="@drawable/my_image"
android:gravity="left"/>
</item>
<item android:top="10dp" android:left="10dp">
<bitmap android:src="@drawable/my_image"
android:gravity="left" />
</item>
<item android:top="20dp">
<bitmap android:src="@drawable/my_image"
android:gravity="left"/>
</item>
<item android:top="20dp" android:left="10dp">
<bitmap android:src="@drawable/my_image"
android:gravity="left" />
</item>
</layer-list>

我编写了以下 block ,但它正在拉伸(stretch)图像。

    InsetDrawable[] layers = new InsetDrawable[this.itemCount];

Resources resources = getResources();

ImageButton imgButton = (ImageButton) findViewById(R.id.btnItems);
int layerTop = 0;
for (int i = 0; i < this.itemCount; i++)
{

int layerLeft = i % 2 == 1 ? 5 : 0;

Drawable dr = resources.getDrawable(R.drawable.my_image);
layers[i] = new InsetDrawable(dr, layerLeft, layerTop, -layerLeft, -layerTop);

layerTop += i % 2 == 1 ? 10 : 0;


}

LayerDrawable layerDrawable = new LayerDrawable(layers);

imgButton.setImageDrawable(layerDrawable);

当我将可绘制 xml 分配给 imgButton 时,它工作正常,没有拉伸(stretch)或任何变化。

ImageButton imgButton = (ImageButton) findViewById(R.id.btnItems);
imgButton.setImageResource(R.drawable.my_layerdrawable);

您有什么想法可以通过代码使图层可绘制吗?

谢谢。

最佳答案

您可以使用 BitmapDrawable。

A Drawable that wraps a bitmap and can be tiled, stretched, or aligned. You can create a BitmapDrawable from a file path, an input stream, through XML inflation, or from a Bitmap object.

您的代码将如下所示:

Drawable[] layers = new Drawable[this.itemCount];
Resources resources = getResources();
ImageButton imgButton = (ImageButton) findViewById(R.id.btnItems);

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

for (int i = 0; i < this.itemCount; i++)
{
Bitmap bm = BitmapFactory.decodeResource(resources, R.drawable.icon);
BitmapDrawable bmd = new BitmapDrawable(bm);
bmd.setGravity(Gravity.TOP);
bmd.setTargetDensity(metrics);
layers[i] = bmd;
}
LayerDrawable layerDrawable = new LayerDrawable(layers);

int layerTop = 0;
for (int i = 0; i < this.itemCount; i++)
{

int layerLeft = i % 2 == 1 ? 5 : 0;
layerDrawable.setLayerInset(i, layerLeft, layerTop, -layerLeft, -layerTop);
layerTop += i % 2 == 1 ? 10 : 0;
}

imgButton.setImageDrawable(layerDrawable);

关于android - 如何通过代码将xml层列表转换为layerdrawable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6950761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com