Android में इमेज पर पिंच-टू-ज़ूम इम्प्लीमेंट करने का तरीका
यह उदाहरण ScaleGestureDetector का उपयोग करके ImageView पर मल्टी-टच ज़ूम (पिंच टू ज़ूम) कार्यक्षमता जोड़ने का तरीका दिखाता है।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project से प्रोजेक्ट बनाएं।
चरण 2: लेआउट फ़ाइल (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/your_image"
android:scaleType="matrix" />
</LinearLayout>
चरण 3: MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private ScaleGestureDetector scaleGestureDetector;
private float scaleFactor = 1f;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
scaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
scaleGestureDetector.onTouchEvent(motionEvent);
return true;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(1f, Math.min(scaleFactor, 10.0f)); // 1x से 10x तक सीमित
imageView.setScaleX(scaleFactor);
imageView.setScaleY(scaleFactor);
return true;
}
}
}
चरण 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
सुधार और बेहतर विकल्प
- मूल कोड में लेआउट और जावा कोड के स्टेप्स गलत क्रम में थे; यहां ठीक किया गया है।
scaleType="matrix"ImageView में जरूरी है ताकि स्केल ट्रांसफॉर्म काम करे।- पैन/ड्रैग सपोर्ट के लिए
onTouchEventमें ट्रांसलेशन लॉजिक जोड़ें। - प्रोडक्शन के लिए PhotoView लाइब्रेरी (github.com/chrisbanes/PhotoView) उपयोग करें जो डबल-टैप ज़ूम, पैन, फ्लिंग सब हैंडल करती है।