scaleType = centerCrop动态

时间:2013-08-15 23:41:44

标签: java android xml imageview crop

我的应用中有一个图库。我的照片来自互联网,所以它们是动态添加的。我的画廊不会将它们裁剪成一个完美的广场。我想这样做只是为了让我的画廊看起来更好。我在我的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,所以这不起作用。谁知道如何以另一种方式做到这一点?动态添加时,我无法找到有关如何操作的信息。提前致谢。

3 个答案:

答案 0 :(得分:2)

如果我没弄错,我们可以使用

imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

答案 1 :(得分:1)

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

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

有关缩放的详细信息,请访问以下链接:

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

答案 2 :(得分:0)

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

首先,强制视图为 square 实际上有点棘手,因为宽度和高度是分开测量的。您可以参考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)以显示裁剪为完美正方形的图像。就是这样!

相关问题