根据比例动态设置View的宽高
最近做按比例裁剪图片时,view的宽高处理有些问题,想到百分比布局但是又没用过,百度了之后看到一段代码:
int width = Screen.getScreenWidth(this);
Log.e("====", bwidth + " " + bHeight + " " + width);
ImageView img = (ImageView) findViewById(R.id.img);
int height = width * bHeight / bwidth;
ViewGroup.LayoutParams para = img.getLayoutParams();
para.height = height;
img.setLayoutParams(para);
看了之后一脸懵,根据这种方式设了之后还真有用,过了一段之后终于想通了,记录一下过程,以免以后再忘记了。
计算如下(个人理解) :
UI和实际显示说明:
关系1:
view 的宽度 和 UI图中边界宽度 的比值 等于 (实际显示效果中) view 的宽度和手机平布的比值,即:
w U i B o a r d W i d t h = r e a l W i d t h S c r e e n W i d t h (1) \cfrac {w}{UiBoardWidth}=\cfrac{realWidth}{ScreenWidth} \tag{1} UiBoardWidthw=ScreenWidthrealWidth(1)
关系2:
w H = r e a l W i d t h r e a l H i g h t (2) \cfrac {w}{H}=\cfrac{realWidth}{realHight} \tag{2} Hw=realHightrealWidth(2)
根据上面(1)和 (2)两个关系式,去掉 realWidth 变量的结果为:
r e a l H i g h t = s c r e e n W i d t h ∗ H U i B o a r d W i d t h realHight = screenWidth * \cfrac{H}{UiBoardWidth} realHight=screenWidth∗UiBoardWidthH
使用如下:
1、layout 中使用 ConstraintLayout 给view设置权重
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txt_percent"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#3c60d7"
android:gravity="center"
android:text="比例设置view"
android:textColor="#ffffff"
android:textSize="20sp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="60dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintWidth_percent="0.5"
/>
</android.support.constraint.ConstraintLayout>
2、class中设置高度:
TextView txtPercent= findViewById(R.id.txt_percent);
//TODO 获取屏幕宽度
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
ViewGroup.LayoutParams layoutParams = txtPercent.getLayoutParams();
int realHight = (int)(screenWidth * 90f / 360f);
layoutParams.height = realHight;
简易UI图及设置后显示效果如下:
3、宽高参数获取:
ViewGroup.LayoutParams layoutParams = txtPercent.getLayoutParams();
int height = layoutParams.height;
int width = txtPercent.getRight() - txtPercent.getLeft();
Display defaultDisplay = getWindowManager().getDefaultDisplay();
Log.i(TAG, "手机屏幕 宽度: " + defaultDisplay.getWidth());
Log.e(TAG, "txtPercent 宽度: " + width + ", 高度:" + height );
输出结果为: