안드로이드

[안드로이드] 이미지뷰 회전시키기

loasd 2023. 1. 13. 01:00
반응형

이미지뷰를 세팅하는 방법은 쉽다.

그냥 액티비티와 XML을 이어주고 .setImageDrawable()을 사용해서 어플에 저장되어 있는 이미지와 이어주거나

XML에서 background를 설정해주는 간단한 방법들이 있다.

그런데 이 이미지를 회전하려면 어떻게 해야될까

 

우선 XML부터 세팅해주도록 하자.

 

    <ImageView
        android:id="@+id/roulette"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="15dp"
        android:clickable="true"
        android:src="@drawable/circle_title"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1"
        app:layout_constraintHorizontal_bias="0.487"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.433"
        app:layout_constraintWidth_percent="0.9" />

이렇게 이미지뷰를 세팅해준다. src에 원하는 이미지를 넣어주면 된다.

 

그리고 액티비티에서 코드를 작성해주면 된다.

    float startDegree = 0f;
    float endDegree = 0f;

	rullet_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rotate(iv_roulette);
            }
        });
        
        
    public void rotate(View v) {
        // ---------- 회전각도 설정 ----------
        startDegree = endDegree;    // 이전 정지 각도를 시작 각도로 설정
        Random rand = new Random(); // 랜덤 객체 생성
        int degree_rand = rand.nextInt(360);    // 0~359 사이의 정수 랜덤생성
        endDegree = startDegree + 360 * 5 + degree_rand;  // 회전 종료각도 설정
        
        // ---------- 애니메이션 실행 ----------
        // 애니메이션 이미지에 대해 초기 각도에서 회전종료 각도까지 회전하는 애니메이션 객체 생성
        ObjectAnimator object = ObjectAnimator.ofFloat(iv_roulette, "rotation", startDegree, endDegree);

        object.setInterpolator(new AccelerateDecelerateInterpolator()); // 애니메이션 속력 설정
        object.setDuration(6000);   // 애니메이션 시간(5초)
        object.start();   // 애니메이션 시작
    }

OnClickListener에 rotate() 메서드를 넣어준다.

 

우선 현재 이미지에서 5바퀴를 돌고 degree_rand를 통해 0 ~ 360사이의 랜덤한 수를 설정한만큼 더 회전한다.

또한 setDuration을 통해 애니메이션이 지속될 시간을 설정해줄 수 있다.

반응형