Tom
Tom

Reputation: 3627

Android scaling imageview from setImageBitmap

I have this code:

<ImageView
android:id="@+id/listitem_logo"
android:layout_width="match_parent"                                   
android:layout_height="wrap_content" />

and

imageview_logo.setImageBitmap(bit); // comes from assets
imageview_logo.setAdjustViewBounds(true);        
imageview_logo.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageview_logo.setBackgroundColor(0x00000000); 
imageview_logo.setPadding(0, 0, 0, 0);
imageview_logo.setVisibility(v.VISIBLE);

When loading the image this way, no scaling seems to have been done. However, if I load an image through setImageDrawable() r.res. the image inside the ImageView is resized. However, I need to use setImageBitmap() since I load my images through assets folder.

Am I missing some setting here? That will make Android resize and scale the bitmap, so it uses the full width of the ImageView? I guess I can do it myself in code, but offhand I would think what I want to do would be supported just by setting some properties.

Upvotes: 10

Views: 16920

Answers (3)

Cristian Scheel
Cristian Scheel

Reputation: 878

With bit as your Bitmap image, you can directly set yout imageView and then crop it using the properties of the imageView as:

    imageview_logo.setImageBitmap(bit);
    imageview_logo.setScaleType(ImageView.ScaleType.CENTER_CROP);

Upvotes: 0

narko
narko

Reputation: 3875

As I needed a bit of time to figure out the complete code to make this work, I am posting a full example here relying on the previous answer:

   ImageView bikeImage = (ImageView) view.findViewById(R.id.bikeImage);
   AssetLoader assetLoader = new AssetLoader(getActivity());
   Bitmap bitmap = assetLoader.getBitmapFromAssets(
                Constants.BIKES_FOLDER + "/" + bike.getName().toLowerCase()
                        .replace(' ', '_').replace('-', '_') + ".png");
   int width = getActivity().getResources().getDisplayMetrics().widthPixels;
   int height = (width*bitmap.getHeight())/bitmap.getWidth();
   bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
   bikeImage.setImageBitmap(bitmap);

Upvotes: 8

Aashish Bhatnagar
Aashish Bhatnagar

Reputation: 2605

Can't trust system for everything specially android which behaves very differently sometimes. You can resize the bitmap.

height = (Screenwidth*originalHeight)/originalWidth;

this will generate the appropriate height. width is equal to screen width as you mentioned.

Bitmap pq=Bitmap.createScaledBitmap(pq,Screenwidth,height, true);

Upvotes: 13

Related Questions