Android scaling imageview from setImageBitmap

╄→尐↘猪︶ㄣ 提交于 2019-12-08 15:47:03

问题


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.


回答1:


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);



回答2:


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);


来源:https://stackoverflow.com/questions/16749044/android-scaling-imageview-from-setimagebitmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!