テキトウな大きさの画像で試したところ、ImageView の大きさが確定してからアニメーションを開始しないと動作しませんでした。(Activity.onCreate 内等ではまだ確定していません。)
以下は drawable 下に sample.png という画像を置き、一度動かしてログから img の大きさが 599x599 なのを確認してから android:transformPivotX="300px"
android:transformPivotY="0px"
として、画像の上辺をピン留めして揺れているようなアニメーションをさせました。
xml では無くコードの(コメントにしてある) img.setPivotX/Y を使えば比率的に指定できるので、先に大きさを見る必要がありません。
java
1package com.teratail.q_nasz1bj07u28hk;
2
3import androidx.appcompat.app.AppCompatActivity;
4
5import android.animation.*;
6import android.os.*;
7import android.util.Log;
8import android.view.ViewTreeObserver;
9import android.widget.ImageView;
10
11public class MainActivity extends AppCompatActivity {
12 private ImageView img;
13
14 @Override
15 protected void onCreate(Bundle savedInstanceState) {
16 super.onCreate(savedInstanceState);
17 setContentView(R.layout.activity_main);
18
19 img = findViewById(R.id.image);
20 img.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
21 @Override
22 public void onGlobalLayout() {
23 img.getViewTreeObserver().removeOnGlobalLayoutListener(this);
24 startAnimation();
25 }
26 });
27 }
28
29 private void startAnimation() {
30 Log.d("MainActivity", "startAnimation: img.getWidth()="+img.getWidth());
31 Log.d("MainActivity", "startAnimation: img.getHeight()="+img.getHeight());
32 //img.setPivotX(img.getWidth() / 2f);
33 //img.setPivotY(0f);
34 AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(MainActivity.this, R.animator.rotation);
35 set.setTarget(img);
36 set.start();
37 }
38}
res/layout/activity_main.xml
xml
1<?xml version="1.0" encoding="utf-8"?>
2<androidx.constraintlayout.widget.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context=".MainActivity">
9
10 <ImageView
11 android:id="@+id/image"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 app:srcCompat="@drawable/sample"
15 android:transformPivotX="300px"
16 android:transformPivotY="0px"
17 app:layout_constraintBottom_toBottomOf="parent"
18 app:layout_constraintEnd_toEndOf="parent"
19 app:layout_constraintStart_toStartOf="parent"
20 app:layout_constraintTop_toTopOf="parent" />
21
22</androidx.constraintlayout.widget.ConstraintLayout>
res/animator/rotation.xml (揺れ幅を大きくしただけです)
xml
1<?xml version="1.0" encoding="utf-8"?>
2<set xmlns:android="http://schemas.android.com/apk/res/android">
3 <objectAnimator
4 android:propertyName="rotation"
5 android:duration="1500"
6 android:valueFrom="-30"
7 android:valueTo="30"
8 android:repeatMode="reverse"
9 android:repeatCount="-1"/>
10</set>
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。