如何缩小Drawable以匹配TextView的宽度?

时间:2012-04-07 15:51:26

标签: android html image layout textview

我正在TextView内呈现带有图片代码的HTML。我尝试在getDrawable()代码中缩放图像失败了。代码看起来像这样。

myTextView.setText(Html.fromHtml(htmlSource, this, this));
@Override public Drawable getDrawable(String url) {
  Drawable.createFromStream((InputStream) new URL(url).getContent(), null);
}

大图像不会缩小以适应屏幕宽度。相反,我只看到图像的最左边部分,而图像的其余部分在屏幕上被裁剪。如何缩小图像以适应屏幕?

我的布局如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myId"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:fillViewport="true" >

        <TextView
            android:id="@+id/myTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:textSize="22dp" />
    </ScrollView>
</LinearLayout>

1 个答案:

答案 0 :(得分:2)

我就这样做了:

@Override public Drawable getDrawable(String url) {
  Drawable drawable = 
     Drawable.createFromStream((InputStream) new URL(url).getContent(), null);
  final float scalingFactor = 
     (float)textView.getMeasuredWidth() / d.getIntrinsicWidth();
  d.setBounds(0, 0, textView.getMeasuredWidth(), 
     (int) (d.getIntrinsicHeight()*scalingFactor));
}

但是,我发现有时候这种技术失败了,因为TextView还没有渲染,getIntrinsicWidth返回0.我还没有解决方案但是如果你使用这个代码,你应该自己检查一下有一些记录。你应该看到有时除以零的例外......