【问题标题】:Resize picture into according to textivew's size根据textivew的大小调整图片大小
【发布时间】:2012-09-29 13:36:44
【问题描述】:

我有一个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并且在可绘制的左图像中看起来很好。

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;

【问题讨论】:

    标签: android android-image


    【解决方案1】:

    您正在寻求一种方法来计算布局后TextView 的确切高度,以便您可以调整drawableLeft 属性的位图大小。 这个问题因以下几个问题而更加复杂:

    1. 如果文本换行为多行,则高度可能会发生巨大变化。
    2. 根据设备硬件屏幕密度,渲染大小 位图的大小将被更改,而与 您缩放/渲染的位图,因此必须采用屏幕密度 计算scaleFactor时考虑在内。
    3. 最后,scaleFactor 不提供精确尺寸的图像请求。 它仅将位图的大小限制为尽可能小的图像 这仍然与您的要求相同或更大,以便保存 记忆。您仍然需要将图像大小调整到确切的高度 你已经计算过了。

    drawableLeft 方法无法克服上述问题,我认为有更好的方法来实现您的预​​期布局,而无需使用 Java 代码调整大小。

    我认为您应该将 TextView 替换为水平方向的 LinearLayout,其中包含 ImageViewTextView。将TextView的高度设置为"WRAP_CONTENT",将ImageView的scaleType设置为“居中”,如下所示:

    android:scaleType="center"
    

    LinearLayout 将具有 TextView 中文本的高度,而 ImageView 的 scaleType 将强制位图在布局期间自动调整大小。这里是可用 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-13
      • 2013-08-28
      • 2018-01-25
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多