需求
一个Activity页面纯展示一张长图,看起来功能是简单的,可还是有些坑存在。记录一下。
坑
要做UI适配,UI给的长图并不能正合适完美展示。宽高比不能确定,在ImageView上设置要么拉伸变形,要么图片不能铺满,与最初的UI设计不符,那这个时候就需要用到Android的屏幕适配了。
解决方案
根据图片的宽高比,计算出并动态设置ImageView的宽和高。
代码
布局:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
android:id="@+id/iv_long_img"
android:layout_width="match_parent"
android:layout_height="match_parent" />
代码实现:
public void setImageViewWideHigh(ImageView imageView, Bitmap bitmap) {
ViewGroup.LayoutParams params = imageView.getLayoutParams();
// 获得bitmap宽高
float bitWidth = bitmap.getWidth();
float bithight = bitmap.getHeight();
float bitScalew = bithight / bitWidth;
// 获得屏幕宽高(有多种方式、用自己喜欢的)
WindowManager manager = this.getWindowManager();
DisplayMetrics outMetrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(outMetrics);
int imgWidth = outMetrics.widthPixels;
int imgHight = outMetrics.heightPixels;
// 根据需求展示长图、宽填满,高按比例设置
params.width = (int) imgWidth;
params.height = (int) (imgWidth * bitScalew);
// ImageView 控件设置
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setAdjustViewBounds(true);
imageView.setLayoutParams(params);
imageView.setImageBitmap(bitmap);
}