ImageView centerCrop 溢出 ImageView 边界?

ImageView centerCrop overflows ImageView bounds?

我有以下布局:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_gravity="top|center"
    android:background="@drawable/rounded_corner"
    android:layout_marginTop="50dp"
    android:layout_width="250dp"
    android:layout_height="350dp">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="270dp"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"
        android:src="@drawable/card_image"
        android:layout_gravity="top"
        android:layout_marginTop="0dp"/>

</FrameLayout>

图像应使用矩形填充图像并缩放图像以保持其纵横比。当我不移动视图时它工作正常:

但是,当我移动视图时,图像绘制在其边界之外:

我正在用这个library移动卡

如何防止 ImageView 在其边界之外绘制图像?

我将此库与 Picasso 一起使用,如下例所示。我对您提供的代码进行了一些修改以使其熟悉。

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_gravity="top|center"
    android:background="@drawable/rounded_corner"
    android:layout_marginTop="50dp"
    android:layout_width="250dp"
    android:layout_height="350dp">

    <!-- Note that I've deleted a lot of properties from the ImageView -->
    <!-- This is because Picasso will do a lot of that for us -->
    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="270dp"
        android:src="@drawable/card_image"
        />
</FrameLayout>

放大视图后,您可以像往常一样使用 findViewById 简单地找到视图。

ImageView imageView = (ImageView) inflatedView.findViewById(R.id.image_view);
// Here comes the Picasso bit
Picasso.with(getActivity()) // You have to provide a Context
       .load(R.drawable.card_image) // Can be a Uri, File or String path as well
       .into(imageView); // Use .into(ImageView view, Callback callback) to register a listener for the image loading.

这将简单地将图像放入 ImageView 而无需修改它。您可以添加 .centerCrop().fit()(下面的示例)和其他漂亮的方法来自动将图像编辑到容器属性中。由于您在示例中使用了 centerCrop,因此我不会深入探讨这些内容,但请参阅我在顶部提供的 Picasso github 页面以获取更多文档。

要中心裁剪或适合图像,请在 load().into() 之间添加方法:

Picasso.with(getActivity())
           .load(R.drawable.card_image)
           .centerCrop()
           .fit()
           .into(imageView);

Picasso 的另一个重要特性是它如何处理缓慢或不成功的加载:您可以添加占位符和错误资源:

Picasso.with(getActivity())
           .load(R.drawable.card_image)
           .placeholder(R.drawable.loading_image)
           .error(R.drawable.error_image
           .into(imageView);

祝你好运!