Android Multi Touch Zoom example
안드로이드 2.2 부터 지원되는 ScaleGestureDetector클래스를 이용하여 이미지를 확대하는 예
layout/main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.example.androidapp.TouchExampleView android:id="@+id/zoomView" android:layout_width="match_parent" android:layout_height="match_parent"/>
</LinearLayout>
TestActivity.java
package com.example.androidapp; import android.app.Activity; import android.os.Bundle; public class TestActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
TouchExampleView.java
package com.example.androidapp; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; public class TouchExampleView extends View { private Drawable mIcon; private float mPosX; private float mPosY; // Android 2.2 부터 지원되는 유용한 클래스 private ScaleGestureDetector mScaleDetector; private float mScaleFactor = 1.0f; public TouchExampleView(Context context) { this(context, null, 0); } public TouchExampleView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TouchExampleView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mIcon = context.getResources().getDrawable(R.drawable.ic_launcher); mIcon.setBounds(0, 0, mIcon.getIntrinsicWidth(), mIcon.getIntrinsicHeight()); // Create our ScaleGestureDetector mScaleDetector = new ScaleGestureDetector(context, new ScaleListener()); } @Override public boolean onTouchEvent(MotionEvent ev) { // Let the ScaleGestureDetector inspect all events. mScaleDetector.onTouchEvent(ev); return true; } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.translate(mPosX, mPosY); canvas.scale(mScaleFactor, mScaleFactor); mIcon.draw(canvas); } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { //mScaleFactor *= detector.getScaleFactor(); // 아래와 동일한 의미
mScaleFactor *= mScaleDetector.getScaleFactor();
invalidate(); return true; } } }