您的位置:首页 > 其它

ImageView宽度填满屏幕,高度自适应

2015-12-11 14:59 405 查看
在CSS中轻松设置width=100%就可以使得图片宽度充满屏幕,高度自适应,那么在Android里面怎样才能实现这种效果呢?

使用默认的ImageView

首先试一下默认的ImageView的效果,布局文件如下activity_main_2.xml:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/test"
android:background="#FF0"/>

</LinearLayout>


MainActivity2.java

public final class MainActivity2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_2);

final ImageView imageView = (ImageView)findViewById(R.id.image);
ViewTreeObserver vto2 = imageView.getViewTreeObserver();
vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
Log.e("TestMeasure","w=" + imageView.getWidth() + "  h=" + imageView.getHeight());
}
});
}
}


test.jpg(正方形998*998)



可以看到,布局文件设置ImageView充满了屏幕,高度自适应,那运行后是我们需要的效果吗?



结果令人失望,虽然ImageView的宽度充满了屏幕,但是图片并没有填满屏幕,这是为什么呢?

原因分析

回头看看ActivityMain2.java中的打印我们看到了ImageView的宽高信息:

TestMeasure﹕ w=1080  h=998

ImageView的高度是和图片的高度一样的,998px。ImageView的宽度和屏幕宽度一样,1080px。

由于ImageView默认的scaleType是fitCenter,将图片按比例扩大(或缩放)到视图的宽(或高)然后居中显示,所以图片宽度没有充满屏幕的原因就是,ImageView的高度不够,它限制了图片的放大倍数。

自定义ImageView
那如何才能将ImageView的高度放大,使得图片宽度刚好充满屏幕呢?答案肯定在onMeasure方法中。

public class ResizableImageView extends ImageView {

public ResizableImageView(Context context) {
super(context);
}

public ResizableImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
Drawable d = getDrawable();

if(d!=null){
// ceil not round - avoid thin vertical gaps along the left/right edges
int width = MeasureSpec.getSize(widthMeasureSpec);
//高度根据使得图片的宽度充满屏幕计算而得
int height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
setMeasuredDimension(width, height);
}else{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}

}


使用自定义的控件显示图片

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<org.sample.ResizableImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/test"
android:background="#FF0"/>

</LinearLayout>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息