【问题标题】:Android calculate bitmap inSampleSize to different target sizeAndroid 将位图 inSampleSize 计算为不同的目标大小
【发布时间】:2011-04-07 16:48:51
【问题描述】:

首先我有一个自定义组件,它是显示来自网络的图片。这是一个简单的布局,包括一个圆形进度条和一个 ImageView。在默认状态下,进度条是可见的,它在图片下载时显示,完成后我隐藏进度条并在 ImageView 中显示图片。它工作得很好,但是在模拟器和 HTC Hero 上我得到了java.lang.OutOfMemoryError: bitmap size exceeds VM budget 错误。我找到了 solution here。但我的问题是,TARGET_WIDTH 和 TARGET_HEIGHT 无法修复,有时是 60x90,有时是 fill_parent x fill_parent,我无法在解码函数中计算这些值。 例如,我使用 layout_width="fill_parent" 在 xml 中添加了我的视图并在 Activity 中使用

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ImageLoader picture = (ImageLoader) findViewById(R.id.picture);
picture.load("http://winportal.net/images/galleries/wallpapers/Earth.jpg");

在加载方法中,我从解决方案中调用解码函数并尝试在这里计算大小:

...
this.onMeasure(0, 0);
Log.d("Log", "Layout width: " + this.getMeasuredWidth());

TARGET_WIDTH =  this.getMeasuredWidth();
...

结果是:“布局宽度:24

我不明白为什么得到 24 是因为进度条的宽度,但布局 - 包括它 - 是 fill_parent 宽度。我尝试了覆盖 onMeasure 方法,但得到了 0。

@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
    int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
    this.setMeasuredDimension(parentWidth, parentHeight);
} 

我也尝试过覆盖 onSizeChanged。它提供了很好的价值,但它会在解码后运行:(

如何计算布局大小?

【问题讨论】:

    标签: android size measure


    【解决方案1】:

    当你调用“this.onMeasure(0, 0);”时您强制视图使用以下规则进行测量 - UNSPECIFIED。您的视图具有以下状态:ProgressBar 可见,ImageView 处于隐藏状态,因此结果将为 24。

    一开始,尝试将FrameLayout 与ProgressBar 和ImageView 一起使用。在那种情况下,您不必关心测量。只需确保图像不会太大(在 OutOfMemory 的情况下)。您可以将图像文件下载到临时文件,然后使用this检查大小,计算适当的采样大小并进行解码,为ImageView设置位图,为ImageView设置比例type

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 2023-02-03
      相关资源
      最近更新 更多