【问题标题】:getting image width and height with picasso library使用毕加索库获取图像宽度和高度
【发布时间】:2014-10-20 18:48:48
【问题描述】:

我正在使用picasso 库将图像下载并加载到 imageView 中。现在我想知道如何在将图像加载到 imageViews 之前获取图像宽度和高度?

我有一个带有适配器的列表视图,其中包含两个 imageView(其中一个是垂直的,另一个是水平的)。取决于图像的宽度和高度,我想将图像加载到其中一个图像视图中。

【问题讨论】:

标签: android image picasso


【解决方案1】:

为我工作。

Picasso.with(context).load(imageLink).into(imageView, new Callback() {
        @Override
        public void onSuccess() {
            Picasso.with(context).load(imageLink).into(new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    int width = bitmap.getWidth();
                    int height = bitmap.getHeight();
                    Log.d("ComeHere ", " W : "+ width+" H : "+height);
                }

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {

                }

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {

                }
            });

        }

        @Override
        public void onError() {

        }
    });

【讨论】:

  • 为什么要在 onSuccess 方法中再次加载图片?
  • 因为他加载了 2 次 URL 图片,第一次他会从 URL 绑定图片,第二次他创建一个假目标来获取宽度高度图片。它将进行同步过程而不是调用 2 操作并且它们不同步
【解决方案2】:

下载后才能获取位图尺寸 - 必须使用同步方法调用,如下所示:

final Bitmap image = Picasso.with(this).load("http://").get();
int width = image.getWidth();
int height = image.getHeight();

在此之后,您可以使用相同的 url 再次调用 load(将从缓存中获取):

 Picasso.with(this).load("http://").into(imageView)

编辑:也许更好的方法:

 Picasso.with(this).load("http://").into(new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                int width = bitmap.getWidth();
                int height = bitmap.getHeight();
                imgView.setImageBitmap(bitmap);
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        });

【讨论】:

  • 只是为了完成答案:您不能在主线程中进行此调用,因为它是同步的。因此,您需要启动例如 AsyncTask,它在后台执行此操作,并在加载图像时返回。
  • 这对于RecyclerView 来说效果不佳,因为毕加索的异步特性加上您的ViewHolders 将被回收(滚动浏览提要时大量图像弹出到不正确的位置,因为它们正在加载到他们的旧视图中)。
  • 使用第二种方式。首先你会得到:“java.lang.IllegalStateException:方法调用不应该从主线程发生”。
猜你喜欢
  • 1970-01-01
  • 2021-10-01
  • 2010-11-18
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
  • 2011-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多