因Android手机屏幕尺寸较多,当imageview宽设置match_parent,高固定时。会导致图片拉伸或裁剪。目前可通过获取图片宽高,动态设置imageview宽高比例,等比例缩放图片。
布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:orientation="vertical">
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter" />
</RelativeLayout>
获取宽高并动态设置宽高:
private int width,height;
//通过Glide获取网络图片宽高
Glide.with(this)
.asBitmap()
.load(imgUrl)
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
width = bitmap.getWidth();
height = bitmap.getHeight();
Log.d(TAG, "width " + width);
Log.d(TAG, "height " + height);
}
@Override
public void onLoadCleared(@Nullable Drawable drawable) {
}
});
//动态设置宽高
ViewGroup.LayoutParams lp = img.getLayoutParams();
lp.width = getIntScreenWidth();
lp.height = lp.width * height / width;
img.setLayoutParams(lp);
Glide.with(this).load(imgUrl).into(img);
//获取屏幕宽高
public static int getIntScreenHeight() {
DisplayMetrics dm = getDisplayMetrics();
return dm.heightPixels;
}
public static int getIntScreenWidth() {
DisplayMetrics dm = getDisplayMetrics();
return dm.widthPixels;
}