Android 如何收缩视图并将其滑入左上角?
我有一个布局资源文件:Android 如何收缩视图并将其滑入左上角?,android,android-animation,android-view,Android,Android Animation,Android View,我有一个布局资源文件: <?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 -->
<?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>
结果是动画发生,但缩略图
在帧布局
中居中
我试过:
- 在布局XML中的
上有和没有ImageView
android:layout_gravity=“top | left”
/translationX(marginPixels)
而不是translationY(marginPixels)
/x(marginPixels)
y(marginPixels)
/translationXBy(marginPixels)
而不是translationYBy(marginPixels)
/x(marginPixels)
y(marginPixels)
缩略图始终居中。如果我注释掉x()
和y()
调用,结果也会居中,这表明出于某种原因,它们被忽略了。相反,如果我注释掉scaleX()
和scaleY()
调用(保留原始列表中的x()
和y()
),则缩略图将被翻译到正确的位置,但它仍然是全尺寸的。如果我在动画之前对缩略图本身使用setX()
和setY()
,并注释掉x()
和y()
调用,那么缩略图最初会定位在正确的位置,但一旦缩放动画开始,我就会回到居中位置
现在,考虑到屏幕大小等等,我当然可以计算出正确的使用值。但是似乎x()
/y()
应该是在ViewPropertyImator
上使用的正确方法,因此我正在尝试找出我的错误所在
更新:此代码有效(或至少非常接近-我还没有实际测量结果以确认精确的像素位置):
我不想知道的是为什么需要这些计算。那么,为什么x
和y
取决于比例?当设置比例时(使用setScale
或通过动画),会考虑轴
值。pivotX
和pivotY
的默认值分别为宽度的一半和高度的一半。因此,当比例
为1.0f
时,任何使用默认轴
的缩放将导致视图
从视图的中心进行缩放
X
和Y
(以及translationX
和translationY
)不受枢轴的影响。您可以看到您的缩略图
实际上被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);
您是否尝试过在缩略图中使用换行内容而不是匹配父项
?不,等等,这很愚蠢;也许诀窍在于你每次打电话的时候交换时间?就像你在更新中做的那样,但是没有设置新位图。@EricBrandwein:好吧,设置新位图是不可协商的——我必须这么做。即使我去掉动画,使用setX()
/setY()
/setScaleX()
/setScaleY()
,我也会得到一个居中的结果。因此,动画结果符合稳态给我的结果,这意味着这对我来说不是一个计时问题。“X和Y(以及translationX和translationY)不受枢轴的影响”——我会用相反的方式表达,X和Y是相对于枢轴的。如果它们没有受到影响,那么更改枢轴不会更改X和Y的行为。也就是说,您的方法是有效的,并且是有意义的。非常感谢!是的,我完全同意。很高兴我能帮忙:)
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);
thumbnail.setVisibility(View.VISIBLE);
thumbnail.setPivotX(0);
thumbnail.setPivotY(0);
thumbnail
.animate()
.scaleX(0.3f)
.scaleY(0.3f)
.x(marginPixels)
.y(marginPixels)
.setDuration(animDuration);