【问题标题】:How to convert a file object into a drawable如何将文件对象转换为可绘制对象
【发布时间】:2015-11-18 06:29:08
【问题描述】:

我习惯于将背景图像设置为我的可绘制对象中的视图。如果我想从文件中设置背景,我应该怎么做?

在这段代码中,我正在扫描一个文件目录,我打算添加我找到的第一个图像文件作为背景。我应该先将图像文件转换为可绘制文件吗?文件扩展名重要吗?

File mFile = new File(stringPath);
File[] mFiles = mFile.listFiles();

for(File aFile : mFiles){

    // Test if aFile is a .jpg or a .png and convert to drawable?

    }

【问题讨论】:

  • 将 BitmapDrawable 与 BitmapFactory 一起使用

标签: android


【解决方案1】:

你可以试试这个:

  public static Drawable foo(String stringPath) {
    File mFile = new File(stringPath);
    File[] mFiles = mFile.listFiles();

    for (File aFile : mFiles) {
        if (isImage(aFile)) {
            return Drawable.createFromPath(aFile.getPath());
        }
    }
    return mPlaceholder;
}


public static boolean isImage(File file) {
    if (file == null || !file.exists()) {
        return false;
    }
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(file.getPath(), options);
    return options.outWidth != -1 && options.outHeight != -1;
}

或者你可以使用其他方式:

public static Bitmap foo(String stringPath) {
    File mFile = new File(stringPath);
    File[] mFiles = mFile.listFiles();

    for (File aFile : mFiles) {

        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(aFile.getAbsolutePath(),bmOptions);
        if(bmOptions.outWidth != -1 && bmOptions.outHeight != -1){
            return bitmap;
        }

    }
    return mPlaceholder;
}


public static void bar(View view, String stringPath) {
    Bitmap bitmap = foo(stringPath);
    BitmapDrawable drawable = new BitmapDrawable(view.getContext().getResources(), bitmap);
    view.setBackground(drawable);
}

【讨论】:

  • 谢谢,我不用先检查aFile是不是图片文件吗?
  • 我想我必须使用类似this
  • 我用的是前一种方法。它工作正常,但我注意到我在日志猫 SkImageDecoder::Factory returned null 中收到此消息我该如何摆脱它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-23
  • 1970-01-01
  • 2018-10-04
  • 1970-01-01
  • 2020-10-26
  • 2023-04-02
相关资源
最近更新 更多