歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中利用OnTouchListener在中ImageView中動態顯示圖片

Android中利用OnTouchListener在中ImageView中動態顯示圖片

日期:2017/3/1 10:20:31   编辑:Linux編程

簡要步驟:

1.新建自己的layout,以便動態添加imageview等控件,並利用setOrientation設置為vertical

final LinearLayout layout2=new LinearLayout(this);

2.引用資源中的圖片,並生成BitmapDrawable

Resources res=getResources();
bmp=BitmapFactory.decodeResource(res,R.drawable.capture);
BitmapDrawable bmp1=new BitmapDrawable(bmp);

其中R.drawable.capture 引用res/drawable文件夾下的capture.bmp,這個圖片是我直接拷到darwable文件下的,正常情況下R.java中的R.drawable下應該有capture了,這個會自動生成,如果沒有自動生成的話,檢查一下Eclipse->project->Automatically是否勾選上

3.生成Imageview, 並設置imageview支持click

ImageView image1=new ImageView(this);
image1.setImageDrawable(bmp1);
image1.setClickable(true);

4.把image1添加到layout2中,並設置setContentView

layout2.addview(image1);

setContentView(layout2);

到這步,已經成功的添加了imageview,並顯示出來,可以下載到手機上看看,這裡就不截圖了

5.接下來,主要是添加OnTouchListener();類似於OnClickListener(),不過需要在new OnTouchListener中實現OnTouch函數。OnTouchListenter是個接口,必須在類中實現它,所以new 了個類OnTouchListener,並在類中implement OnTouch函數。

其中,float startx=0.0f;
float starty=0.0f;
float endx=0.0f;
float endy=0.0f;

是2個坐標點,一個起始點,一個結束點,根據這兩個對角線的點,就可以框選出矩形圖。

Copyright © Linux教程網 All Rights Reserved