Java 使用毕加索将图像调整为全宽和固定高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20823249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:36:48  来源:igfitidea点击:

Resize image to full width and fixed height with Picasso

javaandroidimageviewimage-resizingpicasso

提问by David Rabinowitz

I have a vertical LinearLayout where one of the items is an ImageViewloaded using Picasso. I need to rise the image's width to the full device width, and to display the center part of the image cropped by a fixed height (150dp). I currently have the following code:

我有一个垂直的 LinearLayout,其中一个项目是ImageView使用毕加索加载的。我需要将图像的宽度增加到整个设备宽度,并显示按固定高度 (150dp) 裁剪的图像的中心部分。我目前有以下代码:

Picasso.with(getActivity()) 
    .load(imageUrl) 
    .placeholder(R.drawable.placeholder) 
    .error(R.drawable.error) 
    .resize(screenWidth, imageHeight)
    .centerInside() 
    .into(imageView);

Which values should I put into screenWidthand imageHeight(=150dp)?

我应该将哪些值放入screenWidthand imageHeight(=150dp)?

采纳答案by Jake Wharton

You are looking for:

您正在寻找:

.fit().centerCrop()

What these mean:

这些是什么意思:

  • fit- wait until the ImageViewhas been measured and resize the image to exactly match its size.
  • centerCrop- scale the image honoring the aspect ratio until it fills the size. Crop either the top and bottom or left and right so it matches the size exactly.
  • fit- 等到ImageView已经测量并调整图像大小以完全匹配其大小。
  • centerCrop- 按照纵横比缩放图像,直到它填满尺寸。裁剪顶部和底部或左右,使其大小完全匹配。

回答by Umut ADALI

In some case the fit() is useless. Before you must wait for the width and height measurement to end. So you can use globallayoutlistener. for example;

在某些情况下, fit() 是无用的。在您必须等待宽度和高度测量结束之前。所以你可以使用 globallayoutlistener。例如;

imageView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                Picasso.with(getActivity())
                        .load(imageUrl)
                        .placeholder(R.drawable.placeholder)
                        .error(R.drawable.error)
                        .resize(screenWidth, imageHeight)
                        .fit
                        .centerInside()
                        .into(imageView);
                imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });