【发布时间】:2023-04-04 13:31:01
【问题描述】:
我想实现一个非常简单的视图,我可以通过编程方式完成,但我想知道它是否可以通过专门使用 ConstraintLayout 来完成。
结构是这样的:
- 约束布局
- ImageView1
- ImageView2
一个 ImageView 位于另一个之上,如下图所示:
ImageView1 具有 x1 高度和 w 宽度的可绘制对象。 ImageView2 有一个 x2 高度和 w 宽度的可绘制对象。
我想平等地缩放两个可绘制对象,保持它们的比例,并让 Android 调整宽度以使两个视图占据容器的整个高度。
现在,我正在使用以下函数布局视图后以编程方式进行操作:
private int getWidthForHeight(int height) {
Log.d(TAG, "getWidthForHeight: " + height);
Drawable t = ContextCompat.getDrawable(this, R.drawable.ic_left_menu_mid_bg);
int toh = t.getIntrinsicHeight();
int tow = t.getIntrinsicWidth();
Drawable b = ContextCompat.getDrawable(this, R.drawable.ic_left_menu_bottom_bg);
int boh = b.getIntrinsicHeight();
int bow = b.getIntrinsicWidth();
// height = th + bh
// (toh / tow) * w = th => w = (th * tow) / toh
// (boh / bow) * w = bh => w = (bh * bow) / boh
// (th * tow) / toh = (bh * bow) / boh => boh * th * tow = toh * bh * bow
// boh * th * tow = toh * bh * bow => boh * th * tow = toh * (height - th) * bow
// boh * th * tow = (toh * height - toh * th) * bow
// boh * th * tow = bow * toh * height - bow * toh * th
// th * (boh * tow + bow * toh) = bow * toh * height
// th = (bow * toh * height) / (boh * tow + bow * toh)
// bh = height - th
float th = ((float) (bow * toh * height)) / ((float) (boh * tow + bow * toh));
float bh = height - th;
float width = (th * tow) / (float) toh;
Log.d(TAG, "getWidthForHeight: th = " + th + ", bh = " + bh);
Log.d(TAG, "getWidthForHeight: width = " + width);
return Math.round(width);
}
不过,这对我来说似乎有点 hacky,而且我确信在 Android 中有更简单的方法可以做到这一点。但是,我一直没能找到它。
有人可以对此有所了解吗?
谢谢!
【问题讨论】:
标签: android imageview height width android-constraintlayout