0

我正在努力为游戏创建一个健康栏,但它失败了:提前致谢!

    //there a corresponding ImageView in the layout
    healthLevel = (ImageView) findViewById(R.id.healthbar);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), "res/drawable/health.png");

    //vertical bar cropped from top
    clipDrawable = new ClipDrawable(bitmapDrawable, Gravity.BOTTOM, ClipDrawable.VERTICAL);  
    healthLevel.setImageDrawable(clipDrawable);

    HelperClass.setHealth();
    clipDrawable.setLevel(10000);
    clipDrawable.invalidateSelf();

日志:

11-12 19:32:46.272: W/BitmapDrawable(10524): BitmapDrawable cannot decode res/drawable/health.png

解决方案:

    //there a corresponding ImageView in the layout
    healthLevel = (ImageView) findViewById(R.id.healthbar);
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.health);

    //Convert Bitmap to Drawable
    Drawable bitmapDrawable = new BitmapDrawable(getResources(),bmp); 

    //vertical bar cropped from top
    clipDrawable = new ClipDrawable(bitmapDrawable, Gravity.BOTTOM, ClipDrawable.VERTICAL);  
    healthLevel.setImageDrawable(clipDrawable);

    HelperClass.setHealth();
    clipDrawable.setLevel(10000);
    clipDrawable.invalidateSelf();
4

1 回答 1

1

至于您的问题,从文件路径创建一个BitmapDrawable需要文件的绝对存储路径而不是您的应用程序包的相对路径。

我已经尝试了以下代码,它可以工作。

    final ImageView iv = (ImageView) findViewById(R.id.image_view);
    File file = new File("/storage/sdcard0/Download/ic_launcher.png");
    BitmapDrawable bw = new BitmapDrawable(file.getAbsolutePath());
    iv.setImageDrawable(bw);

但是,我认为您需要的是类似于 a 的东西Bitmap,可以用

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

您可能会发现此教程此链接很有帮助。

于 2013-11-13T02:29:17.493 回答