简体   繁体   中英

Android set imageView background and source

I need a little help with setting an imageview fixed size. Here is the situation that I have. I want all the imageview's size in my application to be resized depending on device's screen width and height. For example I want my image in listview to be with width = 25% from device's display width. For now i can do that like this :

Bitmap bmp=BitmapFactory.decodeResource(acontext.getResources(), R.drawable.transparent_bg);
int width=(int) RPCCommunicator.getPlaceHolderWidth(acontext, 25);
int height=(int) RPCCommunicator.getPlaceHolderHeight(acontext, 20);
Bitmap resizedbitmap=Bitmap.createScaledBitmap(bmp, width, height, true);
mainImg.setImageBitmap(resizedbitmap);

In this sample code I'm just setting a transparent image as default image on my listview item with the sizes which I want. But the thing that I want to do is, to set the size of the imageview, and if image which I receive from server is smaller than the default size,not to fit, just stay centered in this "placeholder". If it's big I'll have to fit it in imageview.

So basically my question is : How can I set ImageView's width and height programmatically without fitting his content. Hope you got what I want.

Thanks in advance!

EDIT:

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (width_in_dp * scale + 0.5f);

Replace width_in_dp with your desired size. Also, you can have a look here: http://developer.android.com/guide/practices/screens_support.html

    DisplayMetrics dm = new DisplayMetrics();      
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);                  
    int screenWidth = dm.widthPixels; 

With this screenWidth you can set view or bitmap sizes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM