2017-08-09 21 views
1

我有先前用於與如何保持縱橫比在它被設置爲一個的ImageView的背景的可繪製XML動畫

imageview.setImageResource(R.drawable.my_image); 

顯示圖像I中的XML定義的scaleType到centerCrop一個ImageView的-layout保持圖像的寬高比

<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保持縱橫比。

有沒有辦法讓動畫保持高寬比?

回答

0
imageview.setImageResource((R.drawable.my_animation); 

您必須設置imageRecource而不是imageBackground。
縮放類型不適用於setBackground。

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

+0

感謝您的迴應。我試圖設置動畫 'imageview.setImageResource((R.drawable.my_animation);' 這個問題是我無法啓動動畫,我試圖用 'animDraw =( AnimationDrawable)imageview.getBackground();' and 'animDraw =(AnimationDrawable)imageview.getDrawable();' 但它不適用於'animDraw.start();' – QitVision

+0

你有gif文件或動畫可繪製文件 –

+0

你可以試試這個或者你的動畫文件http://www.mavengang.com/2016/05/02/gif-animation-android/ –

相關問題