Android:如何保持动画的纵横比
我在图像视图中运行的动画拒绝保持图像帧的纵横比。以下答案内容非常丰富,但似乎对我不起作用: 如何在 ImageView 中缩放图像保持宽高比
这是代码:
private void startAnimation(){
mImageView.setAdjustViewBounds(true);
mImageView.setScaleType(ScaleType.CENTER);
mImageView.setBackgroundResource(R.anim.my_animation);
AnimationDrawable frameAnimation = (AnimationDrawable) mImageView.getBackground();
// Start the animation (looped playback by default).
frameAnimation.start();
}
R.anim.my_animation 只是一个动画列表:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/selected"
android:oneshot="false">
<item
android:drawable="@drawable/photo_1"
android:duration="100" />
<item
android:drawable="@drawable/photo__2"
android:duration="100" />
... and so on...
</animation-list>
The animation I am running inside an imageview refuses to maintain the aspect-ratio of the image frames. The following answers in SO are quite informative, but don't seem to work for me:
How to scale an Image in ImageView to keep the aspect ratio
Here is the code:
private void startAnimation(){
mImageView.setAdjustViewBounds(true);
mImageView.setScaleType(ScaleType.CENTER);
mImageView.setBackgroundResource(R.anim.my_animation);
AnimationDrawable frameAnimation = (AnimationDrawable) mImageView.getBackground();
// Start the animation (looped playback by default).
frameAnimation.start();
}
R.anim.my_animation is just an animation list:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/selected"
android:oneshot="false">
<item
android:drawable="@drawable/photo_1"
android:duration="100" />
<item
android:drawable="@drawable/photo__2"
android:duration="100" />
... and so on...
</animation-list>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要在 imageview 的背景中设置动画可绘制对象,而是使用 src 将其设置在前台并让动画在那里播放。如果您为图像视图设置了合适的比例类型,帧动画中的所有图像都将调整大小,且纵横比保持不变。
Instead of setting the animation drawable in the background of the imageview, set it in the foreground using src and let the animation play there. All images in the frame animation will be resized with aspect ratio intact provided you set a suitable scale type for the imageview.
这有点棘手,但很有效。
我的动画列表中有两张图片
然后我添加了第三张图片(logo0),其大小与 logo1/2 相同,但它是完全透明的。
最后我使用这个 ImageView:
现在我的动画保留了我的图片徽标*的纵横比。
代码是:
它非常简单,只需要额外的虚拟图片给您的资源:没有额外的代码,没有复杂的计算。
This is a bit tricky but it works.
I have two pictures in my animation-list
Then I added a third picture (logo0) that is the same size of logo1/2 but it is fully transparent.
Finally I use this ImageView:
Now my animation preserves the aspect ratio of my pictures logo*.
The code is:
It is very simple and it costs just an extra dummy pictures to you resources: no extra code, no complex calculations.