【问题标题】:How to get resource variable from a string for bitmapFactory如何从 bitmapFactory 的字符串中获取资源变量
【发布时间】:2017-02-12 19:12:33
【问题描述】:

我正在尝试通过图库中图像的位置将资源加载到位图中。我在“drawableId”上设置了正确的文本,但是当它设置为字符串并在位图代码行中引用时出现错误这行代码中带有“a”Bitmap b = BitmapFactory.decodeResource(getResources(), a)

如果我用R.drawable.pg1 替换a,它就可以正常工作。

String a = drawableId.getText().toString();           
Bitmap b = BitmapFactory.decodeResource(getResources(), a);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            postPicture();
        }

        public boolean postPicture() {
            String a = drawableId.getText().toString();

            Bitmap b = BitmapFactory.decodeResource(getResources(), (a));
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/*");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
            try {
                f.createNewFile();
                FileOutputStream fo = new FileOutputStream(f);
                fo.write(bytes.toByteArray());
            } catch (IOException e) {
                e.printStackTrace();
            }
            share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
            startActivity(Intent.createChooser(share, "Share image File"));

关于如何解决此问题的任何想法?提前致谢!

【问题讨论】:

  • 您需要查看文档。所需的第二个参数是一个 int,它是所需的资源 ID,而不是字符串。所以这个 R.drawable.pg1 应该可以正常工作
  • decodeResource 将 int 作为第二个参数,而不是字符串。你真的应该阅读你的错误信息
  • 感谢您的帮助。但是,我正在尝试在 imageSwitcher R.drawable.pg1、R.drawable.pg2 等中的多个图像之间切换。字符串“a”=R.drawable.pg*。但它设置和错误。有不同的方法吗?

标签: android string bitmap android-resources bitmapfactory


【解决方案1】:

用不同的方式试试这个:

int id = getResources().getIdentifier(a, "id", getPackageName());
Drawable drawable = getResources().getDrawable(id);

Bitmap b = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(b); 
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    相关资源
    最近更新 更多