scaleType = centerCrop动态

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了scaleType = centerCrop动态相关的知识,希望对你有一定的参考价值。

我的应用中有一个画廊。我的照片来自互联网,所以它们是动态添加的。我的画廊不会将它们裁剪成一个完美的广场。我想这样做只是为了让我的画廊看起来更好。我在我的XML中试过这个;

 ImageView
        android:id="@+id/phone"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="15dp"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"/>

但是因为我是动态添加图像而不是xml中的src,所以这不会起作用。谁知道如何以另一种方式做到这一点?动态添加时,我无法找到有关如何操作的信息。提前致谢。

答案

如果需要动态缩放图像,可以使用位图的缩放位图方法来指定缩小/缩小图像的大小。像这样的东西:

位图scaledBitmap = Bitmap.createScaledBitmap(unscaledBitmap,wantedWidth,wantedHeight,true);

有关缩放细节,您可以按照以下链接:

http://developer.sonymobile.com/2011/06/27/how-to-scale-images-for-your-android-application/

另一答案

如果我没有弄错,我们可以做到

imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
另一答案

你在GridView放置图像?如果是,则以下内容将起作用。 (如果没有,类似的东西可能会起作用,但我没有测试过)。

首先,强制视图为方形实际上有点棘手,因为宽度和高度是分开测量的。您可以参考Simple way to do dynamic but square layout获取一些想法。最简单的一个(我认为)是创建一个继承自ImageView但覆盖onMeasure()的新视图,例如

public class SquareImageView {

    // add usual constructors here

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // this will change the height to match the measured width
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }
}

然后更改布局xml以创建SquareImageView而不是ImageView的实例。我认为你的其他属性都没问题,特别是android:scaleType="centerCrop"将确保图像填满整个方块。

在此之后,您将图像从任何来源下载到Bitmap实例中,然后调用imageView.setImageBitmap(bitmap)以显示裁剪为完美正方形的图像。就是这样!

以上是关于scaleType = centerCrop动态的主要内容,如果未能解决你的问题,请参考以下文章

android:scaleType="centerCrop"

安卓imageView.scaleType取centerCrop后,再用padding时显示异常?

在 Android 上使用 scaletype centerCrop 时如何调整 ImageView 的裁剪量?

ImageView

android图片的scaleType属性

android:scaleType属性