Giới thiệu
Ví dụ này minh họa cách xoay (rotate) ảnh trong ImageView theo một góc cố định (20 độ) bằng Matrix trong Android.
Bước 1: Tạo dự án mới
Android Studio → File → New Project.
Bước 2: Giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/parent"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:src="@mipmap/ic_launcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textChanger"
android:layout_margin="20dp"
android:textAlignment="center"
android:text="Nhấn để xoay ảnh 20°"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Bước 3: Logic xoay ảnh (src/MainActivity.java)
package com.example.andy.myapplication;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
TextView textChanger;
ImageView imageView;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
textChanger = findViewById(R.id.textChanger);
imageView = findViewById(R.id.imageView);
textChanger.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
rotateImage(imageView);
}
});
}
private void rotateImage(ImageView imageView) {
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); // BẮT BUỘC
matrix.postRotate(20f,
imageView.getDrawable().getBounds().width() / 2f,
imageView.getDrawable().getBounds().height() / 2f
);
imageView.setImageMatrix(matrix);
}
}
Giải thích kỹ thuật
Matrix matrix = new Matrix(); imageView.setScaleType(ImageView.ScaleType.MATRIX); // Bắt buộc để Matrix có hiệu lực matrix.postRotate(20f, centerX, centerY); imageView.setImageMatrix(matrix);
Matrix: Lớp biến đổi hình học 2D (rotate, scale, translate, skew)setScaleType(MATRIX): Bắt buộc - cho phép ImageView dùng Matrix tùy chỉnhpostRotate(degrees, px, py): Xoaydegreesđộ quanh điểm (px,py)getBounds().width()/2: Tâm ảnh (pivot point)
Chạy ứng dụng
Chạy app → Hiển thị ảnh gốc + TextView. Nhấn TextView → Ảnh xoay 20 độ quanh tâm.
Mở rộng: Animation xoay mượt
Dùng ObjectAnimator cho animation xoay liên tục:
ObjectAnimator.ofFloat(imageView, "rotation", 0f, 360f)
.setDuration(1000)
.start();