【问题标题】:Relative translation in property animation in xmlxml中属性动画的相对翻译
【发布时间】:2012-01-20 13:52:55
【问题描述】:

目前我有一个ImageView,它延长了设备的长度并按 3 缩放。显然,屏幕外的边被裁剪了。我希望动画从设备左侧的图像左侧开始,然后将其移动,直到图像的右侧位于设备的右侧。

我可以通过将图像设置为其初始基础然后基本上这样做来实现它们:

  <objectAnimator
    android:propertyName="translationX"
    android:duration="6000"
    android:valueTo="-1280"
    android:valueType="floatType"
  />

但是,这只是因为我知道图像的确切尺寸和我的摩托罗拉 Xoom 的确切尺寸。自然,我希望它可以在任何设备上工作,所以我需要一些不那么硬编码的东西。使用 Tween 动画,它可以正常工作,因为您可以根据其大小的百分比来翻译某些内容。它并不完美,但对于这种效果来说已经足够好了。属性动画似乎没有这个。 translationXX 属性必须有单位。

有没有一种简单的方法可以根据相对位置翻译带有属性动画的视图?我是否必须为每个维度制作单独的动画文件?有没有其他方法可以达到这种效果?我不想自己制作动画。

【问题讨论】:

  • 你知道怎么做吗???

标签: android android-layout android-animation


【解决方案1】:

您能否为您想要支持的单独设备尺寸“存储桶”(例如平板电脑、手机横向等)创建代码,这些“存储桶”具有已知的 dp 宽度。然后你可以在下面使用它来缩放图像(对于某个设备桶宽度,384 是 384dp)并对你需要的 valueTo int 执行类似的操作。

//Get the device screen pixel density so that you can scale
//the image in density independent pixels rather than pixels
final float scale = getActivity().getResources().
getDisplayMetrics().density;

//set the number of dp for the height and width by changing
//the number you multiply the (scale + 0.5f) by e.g. 384
int pixelsh = (int) (384 * scale + 0.5f);
int pixelsw = (int) (384 * scale + 0.5f);

这是将绝对像素转换为 dp 像素的方法。我不知道如何将这些用于您正在做的事情,但至少这是一个开始。

【讨论】:

  • 这还不够详细,因为在编译时无法确定视图的大小(以像素为单位)。我最终放弃了这个想法,只是在已知大小的运行时创建 ObjectAnimators。
【解决方案2】:

您应该在运行时通过传递当前设备屏幕的屏幕尺寸来创建动画。首先获取屏幕尺寸(注意:指标(宽度、高度)会根据设备的旋转而变化)

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

int screenSize = metrics.widthPixels;

然后创建你的 ObjectAnimator:

ObjectAnimator oa = ObjectAnimator.ofFloat(*yourImageView*, "translationX", 0, (Float) screenSize);
oa.setDuration(6000);
oa.start();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 2014-10-03
    相关资源
    最近更新 更多