缩放中央图像回收器视图

Zoom central image recycler view

我有带图片的 RecyclerView。它基于 this solution。使用 Glide 将图像延迟加载到视图中。我需要像这样在中央图像上添加缩放:

我该怎么做?

影响你想要的最直接的方法是扩展LinearLayoutManager。 正如您无疑发现的那样,正确地连接到滚动事件是一件痛苦的事情:

所以让我们扩展管理器。我们将创建一些您可能会公开的参数。

 public class ZoomCenterCardLayoutManager extends LinearLayoutManager {
   // Shrink the cards around the center up to 50%
   private final float mShrinkAmount = 0.5f;
   // The cards will be at 50% when they are 75% of the way between the
   // center and the edge.
   private final float mShrinkDistance = 0.75f;

填写你的构造函数,然后覆盖 scrollHorizontallyBy:

   @Override 
   public int scrollHorizontallyBy(int dx, 
      RecyclerView.Recycler recycler, RecyclerView.State state) {

调用parent的版本并保存行驶距离。我们需要 return 在方法结束时这样做:

      int scrolled = super.scrollHorizontallyBy(dx, recycler, state);

我们将设置一个简单的线性插值。挺好看的。

      float midpoint = getWidth() / 2.f;
      float d0 = 0.f;
      float d1 = mShrinkDistance * midpoint;
      float s0 = 1.f;
      float s1 = 1.f - mShrinkAmount;

遍历所有激活的children控件,运行插值,并设置child的比例。

      for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        float childMidpoint = 
           (getDecoratedRight(child) + getDecoratedLeft(child)) / 2.f;
        float d = Math.min(d1, Math.abs(midpoint - childMidpoint));
        float scale = s0 + (s1 - s0) * (d - d0) / (d1 - d0);
        child.setScaleX(scale);
        child.setScaleY(scale);
      }

      return scrolled;
   }

这几乎就是您所需要的。最后一步是确保在初始化后调用此调整——否则在第一次移动控件之前缩放不会生效:

   @Override
   public void onLayoutChildren(Recycler recycler, State state) {
     super.onLayoutChildren(recycler, state);
     scrollHorizontallyBy(0, recycler, state);
   }

 }

仅此而已。超级响应,您可以将这个新的布局管理器放入任何水平回收器中。