Search code examples
androidimageassets

Android: Image from assets folder is smaller than it should be


I have problem when I try to set an image to a ImageView browsed from assets folder. When I place the same image in the drawable folder and use imageView.setImageResource(R.id.image); it is larger and fits the screen better than the image browsed by the previous method. Is there a way to resize the image so that it fits the screen exactly the same way as usual.

Here is the layout file and the code in java.

        AssetManager manager = getActivity().getAssets();       
        InputStream input = null;
        try {
            input = manager.open("images/" + mQuestion.getQImage() + ".png");
        } catch (IOException e) {
            e.printStackTrace();
        }
        Bitmap image = BitmapFactory.decodeStream(input);
        ImageView qImageView = (ImageView) questionView.findViewById(R.id.ImageView_qImage);
        qImageView.setImageBitmap(image);



  <ImageView
    android:id="@+id/ImageView_qImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="@dimen/questionTopBottomMargin"
    android:background="@color/radioButtonStrokeColor"
    android:contentDescription="@string/hello_world"
    android:padding="1px"
    android:scaleType="fitXY" />

Solution

  • When you place an image in drawable folder then the images are classified on density of screen while if you put images in assest folder then android need to calculate density.

    If you want to use images from assest folder then this code will help you.

    Options opts = new BitmapFactory.Options();
    opts.inDensity = DisplayMetrics.DENSITY_HIGH;
    drawable = Drawable.createFromResourceStream(context.getResources(), null, is, srcName, opts);
    

    see here

    Image loaded from assets folder comes in different size than res/drawable

    Android: Accessing images from assets/drawable folders