1

我有一个以编程方式创建的 ImageView。我想将整个 imageView 作为可绘制对象。当我执行以下操作时,我会返回 null

private Drawable getDrawable(Data data) {
    ImageView image = new ImageView(context);
    image.setBackground(data.getColor());
    image.setImageDrawable(data.getIcon());
    return image.getDrawable();
}

现在,我还怀疑我的方法只会返回 imageView 的可绘制部分,没有背景。

如何将整个 ImageView 作为可绘制对象?

更新:

以下仍然不起作用:

private Drawable getDrawable(Data data) {
    ImageView image = new ImageView(context);
    image.setBackground(data.getColor());
    image.setImageDrawable(data.getIcon());
    image.setDrawingCacheEnabled(true);
    image.buildDrawingCache();
    Drawable drawable = new BitmapDrawable(context.getResources(), image.getDrawingCache());
    image.setDrawingCacheEnabled(false);
    return drawable;
}
4

2 回答 2

1

我很确定这可行,但我自己没有测试过。尝试使用image.getDrawingCache()来获取呈现的Bitmap内容。View您可能需要使用image.setDrawingCacheEnabled(true). 从那里,您可以使用 aBitmapDrawable将其转换BitmapDrawable类型。这是Android 文档中有关绘制缓存的一些信息。这里有一些关于.BitmapDrawable

于 2013-08-16T17:57:37.523 回答
0

在调用之前,image.buildDrawingCache()您需要测量和布局图像。您可以尝试以下代码。

int ws = MeasureSpec.makeMeasureSpec(imageWidth, MeasureSpec.EXACTLY);
int hs = MeasureSpec.makeMeasureSpec(imageHeight, MeasureSpec.EXACTLY);
image.measure(ws, hs);
image.layout(0, 0, image.getMeasuredWidth(), image.getMeasuredHeight());
于 2013-08-17T13:54:33.997 回答