根据TextView的大小调整图片尺寸

3

我有一个TextView,我在其中设置了一张图片作为drawableLeft

<TextView
   android:id="@+id/imgChooseImage"
   android:layout_width="fill_parent"
   android:layout_height="0dp"
   android:layout_weight="3"
   android:background="@drawable/slim_spinner_normal"
   android:drawableLeft="@drawable/ic_launcher"/>

我希望您能告诉我在Java代码中应该写什么来动态替换新图像,以便图像不超过 TextView ,并且在drawable左侧图像中看起来良好。

scalefactor 中应该使用什么?

int scaleFactor = Math.min();

以下是Java代码

BitmapFactory.Options bmOptions = new BitmapFactory.Options();
// If set to true, the decoder will return null (no bitmap), but
// the out... fields will still be set, allowing the caller to
// query the bitmap without having to allocate the memory for
// its pixels.
bmOptions.inJustDecodeBounds = true;
int photoW = hListView.getWidth();
int photoH = hListView.getHeight();

// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / 100, photoH / 100);

// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), Const.template[arg2],bmOptions);

Drawable draw = new BitmapDrawable(getResources(), bitmap);

/* place image to textview */
TextView txtView = (TextView) findViewById(R.id.imgChooseImage);
txtView.setCompoundDrawablesWithIntrinsicBounds(draw, null,null, null);
position = arg2;
1个回答

0
您正在寻找一种计算TextView在布局后的确切高度的方法,以便您可以调整drawableLeft属性的位图大小。 该问题由几个问题复杂化:
  1. 如果文本换行到多行,则高度可能会发生巨大变化。
  2. 根据设备硬件屏幕密度,位图的呈现大小将发生更改,无论您缩放/渲染的位图的确切大小如何,因此在计算scaleFactor时必须考虑屏幕密度。
  3. 最后,scaleFactor不能提供精确大小的图像请求。它仅限制位图的大小为与您的请求相同或更大的最小可能图像,以节省内存。您仍然需要将图像调整为您计算出的确切高度。
drawableLeft方法无法克服上述问题,我认为有更好的方法可以实现您想要的布局,而无需使用Java代码进行调整大小。

我认为你应该用一个水平方向的LinearLayout来替换你的TextView,其中包含一个ImageView和一个TextView。将TextView的高度设置为"WRAP_CONTENT",并将ImageView的scaleType设置为"center",像这样:

android:scaleType="center"

LinearLayout 的高度将与 TextView 中的文本和 ImageView 的 scaleType 强制 Bitmap 在布局期间自动调整大小。这里是可用 scaleTypes 的参考:ImageView.ScaleType

当然,您需要在 XML 中调整 LinearLayout、ImageView 和 TextView 的布局参数,使它们居中、对齐并以您想要的确切方式定向。但是,至少您只需要做一次。

由于似乎您将从应用程序资源中加载照片到 ImageView 中,因此您可能知道图像不是很大,因此可以直接打开 Bitmap,或使用 inSampleSize = scaleFactor = 1。否则,如果图像特别大或者出现 OutOfMemoryError 异常,则按以下方式计算 scaleFactor

int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
    if (width > height) {
        inSampleSize = Math.round((float) height / (float) reqHeight);
    } else {
        inSampleSize = Math.round((float) width / (float) reqWidth);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接