根据ImageView图片大小设置TextSize

setTextSize accordingly to ImageView's image size

我得到了一个带有 ImageView 和 TextView 的水平方向的 LinearLayout。 TextView 有一个 1 位或 2 位数字的文本。

我需要的是将 TextView 的文本大小设置为与 ImageView 图像的高度完全相同。

我知道我可以获得 ImageView 的图像高度,但是我怎样才能使 textSize 相应地高?

为(图像视图和文本视图)提供恒定的高度宽度...或尝试 scaleType="fitxy"...

你可以试试:

float height = imageView.getHeight();
TextView tv = new TextView(context);
tv.setTextSize(height)

我不确定这是否完全符合您的要求,但这是我看到的最明显的起点。

View.getHeight():

Return the height of your view. Returns

Returns
    The height of your view, in pixels.

TextView.setTextSize(float):

Set the default text size to the given value, interpreted as "scaled pixel" units. This size is adjusted based on the current density and user font size preference.

Parameters
   size    The scaled pixel size.

这基本上意味着您需要将高度 (px) 转换为文本高度 (sp):

float density = getResources().getDisplayMetrics().scaledDensity;
float textHeight = imageHeight / density;

好吧,我发现了以下情况:

首先我们需要找到 ImageView 图像的实际高度 - 它没有 ImageView 高,所以这里解释得很好:How to get the width and height of an android.widget.ImageView?

接下来我们设置文本的高度:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 
imageView.getMeasuredHeight()*(imageView.getMeasuredHeight()/
imageView.getMeasuredWidth()));

这意味着我们以原始像素设置 textSize,然后我们获取高度并将其乘以图片的高宽比,这样 TextView 的文本大小将与图像完全一样高