【问题标题】:How to keep the aspect ratio in a drawable XML animation that is set to background of an ImageView如何在设置为 ImageView 背景的可绘制 XML 动画中保持纵横比
【发布时间】:2017-08-09 13:15:30
【问题描述】:

我有一个以前用来显示图像的 ImageView

imageview.setImageResource(R.drawable.my_image);

我在 XML 布局中将 scaleType 定义为 centerCrop 以保持图像的纵横比

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image_view"
        android:src="@drawable/my_image"
        android:scaleType="centerCrop" />

现在我需要在 ImageView 中使用 drawable animation 并将其设置为 imageView 的背景。

布局文件:

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image_view"
        android:src="@android:color/transparent"
        android:scaleType="centerCrop" />

Java:

AnimationDrawable animDraw;

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  ImageView imageview = (ImageView) findViewById(R.id.image_view);
  imageview.setBackgroundResource(R.drawable.my_animation);
  animDraw = (AnimationDrawable) imageview.getBackground();
}

public boolean onTouchEvent(MotionEvent event) {
  if (event.getAction() == MotionEvent.ACTION_DOWN) {
    animDraw .start();
    return true;
  }
  return super.onTouchEvent(event);
}

my_animation 可绘制

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="true">
    <item android:drawable="@drawable/my_image1" android:duration="150" />
    <item android:drawable="@drawable/my_image2" android:duration="150" />
    <item android:drawable="@drawable/my_image3" android:duration="150" />
</animation-list>

动画效果很好,但可绘制对象现在设置为背景,我无法更改它的 scaleType 以保持纵横比。

有没有办法让动画保持纵横比?

【问题讨论】:

    标签: android android-layout android-animation


    【解决方案1】:
    imageview.setImageResource((R.drawable.my_animation);
    

    您必须设置 imageRecource 而不是 imageBackground。
    比例类型不适用于 setBackground。

    更多:How do I set an ImageViews source programmatically in Android?

    【讨论】:

    • 感谢您的回复。我试图用imageview.setImageResource((R.drawable.my_animation); 设置动画这个问题是我无法启动动画。我尝试使用animDraw = (AnimationDrawable) imageview.getBackground();animDraw = (AnimationDrawable) imageview.getDrawable(); 获取对动画的引用,但它不适用于animDraw.start();
    • 你可以试试这个或者你的动画文件mavengang.com/2016/05/02/gif-animation-android
    • 我有一个可绘制文件“my_animation.xml”,显示在原始帖子中。它只是指定帧图像及其持续时间。如果设置在背景上,此动画效果很好,但如果使用 setImageResource 设置,则不会运行。我可以尝试你的 gif 方法,但我想我可以将动画设置为背景,然后重新编程 ImageView 的布局参数以匹配动画的纵横比。那么对于不同的屏幕尺寸,拉伸不会成为问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    相关资源
    最近更新 更多