यह उदाहरण दर्शाता है कि ImageView में इमेज को एक एंगल से कैसे घुमाया जाए।
इमेज रोटेशन का उदाहरण
चरण 1 - नया प्रोजेक्ट बनाएं
Android Studio में एक नया प्रोजेक्ट बनाएं: File → New Project पर जाएं और आवश्यक विवरण भरें।
चरण 2 - लेआउट XML में कोड जोड़ें
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="Initial text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
उपरोक्त कोड में, हमने ImageView और TextView लिया है। जब उपयोगकर्ता TextView पर क्लिक करता है, तो इमेज 20-डिग्री एंगल पर घूम जाएगी।
चरण 3 - MainActivity.java में कोड जोड़ें
src/MainActivity.java में निम्नलिखित कोड जोड़ें:
package com.example.andy.myapplication;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private TextView textChanger;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textChanger = findViewById(R.id.textChanger);
imageView = findViewById(R.id.imageView);
textChanger.setOnClickListener(v -> rotateImage(imageView));
}
private void rotateImage(ImageView imageView) {
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); // आवश्यक
matrix.postRotate(20f,
imageView.getDrawable().getBounds().width() / 2f,
imageView.getDrawable().getBounds().height() / 2f);
imageView.setImageMatrix(matrix);
}
}
उपरोक्त कोड में, हमने rotateImage() का उपयोग किया है और ImageView पास किया है:
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); // आवश्यक
matrix.postRotate(20f,
imageView.getDrawable().getBounds().width() / 2f,
imageView.getDrawable().getBounds().height() / 2f);
imageView.setImageMatrix(matrix);
ऐप चलाएं
अपने Android डिवाइस को कंप्यूटर से कनेक्ट करें और ऐप चलाएं। "Initial text" TextView पर क्लिक करने पर, इमेज 20 डिग्री घूम जाएगी।