代码之家  ›  专栏  ›  技术社区  ›  CommonsWare

如何缩小视图并将其滑入左上角?

  •  6
  • CommonsWare  · 技术社区  · 10 年前

    我有一个布局资源文件:

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent">
    
      <!-- other widget here -->
    
      <ImageView
        android:id="@+id/thumbnail"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFFFFFFF"
        android:layout_gravity="top|left"
        android:visibility="gone"/>
    
    </FrameLayout>
    

    在某个时间点,这个布局将显示在我的活动中。此时,我将设置 thumbnail ImageView View.VISIBLE ,然后我想将其动画化为占据屏幕宽度/高度的30%,位于 marginPixels 从左上角(在我的测试设备上, 边距像素 为48)。这将暴露潜在的 View ,除了由 缩略图 .

    为此,我有以下Java:

    thumbnail.setVisibility(View.VISIBLE);
    thumbnail
      .animate()
      .scaleX(0.3f)
      .scaleY(0.3f)
      .x(marginPixels)
      .y(marginPixels)
      .setDuration(animDuration);
    

    结果是动画发生了,但是 缩略图 位于 FrameLayout .

    我尝试过:

    • 既有也没有 android:layout_gravity="top|left" 图片框 在布局XML中

    • translationX(marginPixels) / translationY(marginPixels) 而不是 x(marginPixels) / y(marginPixels)

    • translationXBy(marginPixels) / translationYBy(marginPixels) 而不是 x(边距像素) / y(边距像素)

    似乎都没有效果。这个 缩略图 始终居中。如果我注释掉 x() y() 呼叫,结果也是集中的,这表明出于某种原因,它们被忽略了。相反,如果我将 scaleX() scaleY() 呼叫(离开 x() y() 如原始列表所示) 缩略图 被翻译到正确的位置,但它仍然是全尺寸的。如果我使用 setX() setY() 缩略图 在动画之前对其本身进行注释 x() y() 呼叫 缩略图 最初是定位在正确的位置,但一旦缩放动画开始,我就回到了中心。

    现在,给定屏幕大小等等,我当然可以计算出要使用的正确值。但看起来好像 x() / y() 应该是在 ViewPropertyAnimator ,所以我想弄清楚我哪里出错了。

    更新 :此代码有效(或至少接近-我还没有实际测量结果以确认精确的像素位置):

    int x=(int)(-0.35f*(float)bmp.getWidth())+marginPixels;
    int y=(int)(-0.35f*(float)bmp.getHeight())+marginPixels;
    
    thumbnail.setVisibility(View.VISIBLE);
    thumbnail.setImageBitmap(bmp);
    thumbnail
      .animate()
      .x(x)
      .y(y)
      .scaleX(0.3f)
      .scaleY(0.3f)
      .setDuration(animDuration);
    

    我不明白的是为什么需要这些计算。借条,为什么 x y 取决于规模?

    1 回复  |  直到 10 年前
        1
  •  6
  •   Bartek Lipinski    10 年前

    设置时 scale (与 setScale 或通过动画), pivot 正在考虑价值观。的默认值 pivotX pivotY width 和一半的 height (分别)。因此,任何默认缩放 pivots 将导致 View 从(或朝向) 看法 规模 1.0f .

    X Y (以及 translationX translationY )不受影响 枢轴 。您可以看到 thumbnail 实际上 marginPixels (垂直和水平)。

    如果您尝试以下代码,您将看到一切都按预期工作。

    thumbnail.setVisibility(View.VISIBLE);
    thumbnail.setPivotX(0);
    thumbnail.setPivotY(0);
    thumbnail
      .animate()
      .scaleX(0.3f)
      .scaleY(0.3f)
      .x(marginPixels)
      .y(marginPixels)
      .setDuration(animDuration);