android - 将 ImageView 转换为 Canvas 的 Drawable

标签 android android-layout imageview drawable android-canvas

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

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;
}

最佳答案

我很确定这行得通,但我自己还没有测试过。尝试使用 image.getDrawingCache() 获取 View 呈现的内容的 Bitmap。您可能需要使用 image.setDrawingCacheEnabled(true) 启用绘图缓存。从那里,您可以使用 BitmapDrawableBitmap 转换为 Drawable 类型。这是来自 Android documentation 的一些信息在绘制缓存上。和 here是关于 BitmapDrawable 的一些信息。

关于android - 将 ImageView 转换为 Canvas 的 Drawable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18279103/

相关文章:

android - 为 android 构建 ionic/react - 无效的项目类型 "react"

android - 静默安装 Android Studio?

android - onLocationChanged() 被调用太多次,即使设备没有移动

Android 将项目一个接一个地添加到 LinearLayout 中

android - 应用启动后 Imageview 可见 3 秒

java - 在图像上添加标记/图钉的最佳方法是什么?

android - 在 OkHttp 中将整个 byteStream/inputStream 响应读取到内存中的最简单方法是什么?

android - 如何从代码中设置 "app:layout_columnWeight"?

android - 背景渐变与每页上的图像相结合

android - 在 SurfaceView 中显示 ImageView