ImageView和onTouchListener实现,点击查看图片细节
这是来自疯狂android讲义上的例子,其实没啥意思。就是用监听器获取到手指的坐标,然后根据这个坐标开始绘制一个图片。(这里的绘制方式有些问题,所以凑合看看吧。)
首先,还是布局文件(两个ImageView)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView01_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Large Text"/> <ImageView android:id="@+id/imageView01_id" android:layout_width="match_parent" android:layout_height="300dp" android:src="@drawable/kale" android:scaleType="fitXY"/> <ImageView android:id="@+id/imageView02_id" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/kale" android:scaleType="fitXY"/> </LinearLayout>
MainActivity.java
package com.kale.imageview02; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends Activity { ImageView iV01,iV02; TextView tV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewInit(); } public void viewInit() { iV01 = (ImageView)findViewById(R.id.imageView01_id); iV02 = (ImageView)findViewById(R.id.imageView02_id); tV = (TextView)findViewById(R.id.textView01_id); iV01.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_MOVE) { tV.setText("x坐標 = "+event.getX()+" y坐標 = "+event.getY()); } if(event.getAction() == MotionEvent.ACTION_DOWN) { //得到圖片01的bitmapDrawable對象 BitmapDrawable bitmapDrawable = (BitmapDrawable)iV01.getDrawable(); //獲取到位圖 Bitmap bitmap = bitmapDrawable.getBitmap(); //定義縮放比例 double scale = bitmap.getWidth()/320.0; //定義繪製的開始坐標 int x = (int)(event.getX() * scale); int y = (int)(event.getY() * scale); if(x + 120 > bitmap.getWidth()) { x = bitmap.getWidth() - 120; } if(y + 120 >bitmap.getHeight()){ y = bitmap.getHeight() - 120; } //顯示圖片的指定區域 iV02.setImageBitmap(Bitmap.createBitmap(bitmap,x,y,120,120)); } //如果設置為false,那麼移動坐標就不會顯示 return true; } }); } }