【问题标题】:Are there any alternatives to getting a bitmap from XML other than using BitmapDrawable除了使用 BitmapDrawable 之外,还有其他方法可以从 XML 获取位图吗
【发布时间】:2015-01-06 03:01:31
【问题描述】:

我目前在我的应用程序中使用 BitmapDrawable,但不幸的是,此实现在 Lollipop 中似乎有些损坏(在 LP 之前它运行良好,关于该问题有一个单独的问题)。

所以,好的,我有一个 XML 文件,基本上是这样的:

backgrounds.xml

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/backgrounds_xlarge" />

上面是一个 XML 文件(别名),它指向一个实际的 png 文件。

在我的代码中,我得到这样的位图:

代码

BitmapDrawable bd = (BitmapDrawable) view.getResources().getDrawable(R.drawable.backgrounds);
backgrounds = bd.getBitmap();

这个问题是想问是否有另一种方法来获取这个位图?请注意,BitmapFactory 对我没有好处,因为我必须能够通过上面显示的 xml 别名获取此位图。

我已经阅读了Offical docs on creating XML Aliases,但不幸的是,它们在解释如何访问位图方面有些欠缺。

任何帮助或建议表示赞赏。

【问题讨论】:

    标签: android xml bitmap alias bitmapdrawable


    【解决方案1】:

    这是从BitmapDrawable 获取Bitmap 的另一种方法,使用Canvas

        BitmapDrawable bd = (BitmapDrawable) view.getResources().getDrawable(R.drawable.backgrounds);
        Bitmap backgrounds = Bitmap.createBitmap(bd.getIntrinsicWidth(), bd.getIntrinsicHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(backgrounds); 
        bd.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        bd.draw(canvas);
    

    【讨论】:

    • 感谢@samgak - 这确实创建了位图,不幸的是,我仍然遇到同样的问题,我将为此打开另一个问题,但您的回答提供了问题的解决方案 -所以,接受了,谢谢!
    猜你喜欢
    • 2019-09-14
    • 2018-04-21
    • 2018-03-01
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    相关资源
    最近更新 更多