Android中很多开发者都遇到过一个问题,那就是想动态设定imageview的大小。笔者也曾经遇到过这个问题,经过查阅资料后发现,
ImageView在设置了图片资源后是无法改变其大小的。但是有一种使用场景,当开发者希望从sd卡中动态加载一幅图片并动态显示时,
是可以通过设置imageview的大小来保证图片资源的比例正常。
例如:想横向满屏显示一副图片,那么如何确定图片的高呢?如果设置不当,有可能会导致图片变形。笔者经过研究,找出了一种方法,步骤如下:
1. 在布局文件中定义imageview,但不为其设置资源。
<LinearLayout
android:orientation="vertical"
android:layout_below="@id/title_bar"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/topImageview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
2. 在activity的初始化代码中,初始化imageview 并设定大小:
public void initTopImageView(View view) {
ImageView imageTopview = (ImageView)view.findViewById(R.id.topImageview);
WindowManager windowManager = mParent.getWindowManager();
Display display = windowManager.getDefaultDisplay();
int imageWidth = display.getWidth();
int imageHeight = 0;
BitmapFactory.Options option = new BitmapFactory.Options();
option.inJustDecodeBounds = true;
Bitmap myMap = BitmapFactory.decodeStream(getResources().openRawResource(R.raw.landing_hot_product_1));
imageHeight = (imageWidth*myMap.getHeight())/myMap.getWidth();
imageTopview.setScaleType(ImageView.ScaleType.FIT_XY);
imageTopview.setLayoutParams(new LinearLayout.LayoutParams(imageWidth,imageHeight));
imageTopview.setImageResource(R.raw.landing_hot_product_1);
myMap.recycle();
}
在给imageview设置图片资源之前,根据比例关系动态计算图片的宽和高,并设置给imageview.
==============================================================================================
貌似最近有发现了一种更加简单直接的方法,附在后面吧:
将iamgeview控件的长和宽设为wrap_content.然后通过控制加载时的图像的长和宽,就可以控制imageview的大小了。