2011-05-16 34 views
8

我在imageview中运行的动画拒绝保持图像帧的纵横比。在所以下面的答案是相当有价值的信息,但似乎并没有为我工作: How to scale an Image in ImageView to keep the aspect ratioAndroid:如何在动画中保持纵横比

下面是代码:

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> 
+1

根据您引用的问题,该解决方案使用了XML布局。发布您的XML布局,以便我们可以验证您是否正确定义了参数。 – user432209 2011-05-16 16:56:21

+0

@ user432209:+1。你帮我弄清楚我的错误。我已经将imageview的高度和宽度设置为绝对值(因为它显示了除动画之外的其他东西)。删除可以解决问题。谢谢! – OceanBlue 2011-05-16 18:37:52

回答

0

这有点棘手,但它的工作原理。 我有我的动画列表两张图片

<animation-list xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/selected" android:oneshot="false"> 
    <item android:drawable="@drawable/logo1" android:duration="5000" /> 
    <item android:drawable="@drawable/logo2" android:duration="300" /> 
</animation-list> 

然后,我增加了第三个画面(logo0)即是LOGO1/2的大小相同,但它是完全透明的。 最后,我用这个ImageView的:

<ImageView 
    android:id="@+id/imageViewLogo" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:adjustViewBounds="true" 
    android:layout_margin="5dp" 
    android:src="@drawable/logo0" 
/> 

现在我的动画保存我的图片标志的宽高比*。

的代码是:

@Override 
    public void onCreate(Bundle savedInstanceState) { 
    ... 
    imageView = (ImageView) findViewById(R.id.imageViewLogo); 
    imageView.setBackgroundResource(R.drawable.logo_animation); 
    ... 


    public void onWindowFocusChanged (boolean hasFocus) { 
    super.onWindowFocusChanged(hasFocus); 
    AnimationDrawable frameAnimation = (AnimationDrawable) imageView.getBackground(); 
    if(hasFocus) { frameAnimation.start(); } else { frameAnimation.stop(); } 
    } 

这是非常简单的,它的成本只是一个额外的虚拟图像到你的资源:没有多余的代码,没有复杂的计算。

10

不是在imageview的背景中设置可绘制动画,而是使用src在前景中设置它,并让动画在那里播放。如果您为图像视图设置了合适的比例类型,则框架动画中的所有图像都将调整为纵横比不变。

private void startAnimation(){ 
    mImageView.setAdjustViewBounds(true); 
    mImageView.setScaleType(ScaleType.CENTER); 
    mImageView.setImageDrawable(getResources().getDrawable(R.anim.my_animation)); 

    AnimationDrawable frameAnimation = (AnimationDrawable) mImageView.getDrawable(); 

    // Start the animation (looped playback by default). 
    frameAnimation.start(); 
} 
+0

我提高了解决问题的答案。注意,你只能简单地使用'mImageView.setImageResource(R.anim.my_animation)'。 – 2015-07-28 08:20:01

+0

谢谢,你救了我的一天:) – iscariot 2016-11-24 09:47:56

相关问题