1 /* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.example.android.touchexample; 17 18 import android.content.Context; 19 import android.graphics.Canvas; 20 import android.graphics.drawable.Drawable; 21 import android.util.AttributeSet; 22 import android.view.MotionEvent; 23 import android.view.View; 24 25 public class TouchExampleView extends View { 26 private Drawable mIcon; 27 private float mPosX; 28 private float mPosY; 29 30 private VersionedGestureDetector mDetector; 31 private float mScaleFactor = 1.f; 32 TouchExampleView(Context context)33 public TouchExampleView(Context context) { 34 this(context, null, 0); 35 } 36 TouchExampleView(Context context, AttributeSet attrs)37 public TouchExampleView(Context context, AttributeSet attrs) { 38 this(context, attrs, 0); 39 } 40 TouchExampleView(Context context, AttributeSet attrs, int defStyle)41 public TouchExampleView(Context context, AttributeSet attrs, int defStyle) { 42 super(context, attrs, defStyle); 43 mIcon = context.getResources().getDrawable(R.drawable.icon); 44 mIcon.setBounds(0, 0, mIcon.getIntrinsicWidth(), mIcon.getIntrinsicHeight()); 45 46 mDetector = VersionedGestureDetector.newInstance(context, new GestureCallback()); 47 } 48 49 @Override onTouchEvent(MotionEvent ev)50 public boolean onTouchEvent(MotionEvent ev) { 51 mDetector.onTouchEvent(ev); 52 return true; 53 } 54 55 @Override onDraw(Canvas canvas)56 public void onDraw(Canvas canvas) { 57 super.onDraw(canvas); 58 59 canvas.save(); 60 canvas.translate(mPosX, mPosY); 61 canvas.scale(mScaleFactor, mScaleFactor); 62 mIcon.draw(canvas); 63 canvas.restore(); 64 } 65 66 private class GestureCallback implements VersionedGestureDetector.OnGestureListener { onDrag(float dx, float dy)67 public void onDrag(float dx, float dy) { 68 mPosX += dx; 69 mPosY += dy; 70 invalidate(); 71 } 72 onScale(float scaleFactor)73 public void onScale(float scaleFactor) { 74 mScaleFactor *= scaleFactor; 75 76 // Don't let the object get too small or too large. 77 mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f)); 78 79 invalidate(); 80 } 81 } 82 } 83