在今天的學習中堪置,使用了橫向的滾動控件 HorizontalScrollView张惹,并在其中添加一個橫向的LinearLayout 來實現(xiàn)動態(tài)調用系統(tǒng)相機舀锨,拍攝并保存圖片的一個邏輯宛逗,下面我就來進行詳細的介紹。
基本思路就是 保存拍照返回的路徑集合(List<ImagePath>)替蔬,根據路徑集合中的內容生成Bitmap(位圖)屎暇,然后對圖片進行一定的處理(縮放,壓縮)根悼。接著創(chuàng)建 ImageView 實例,并將ImageView 實例添加到 LinearLayout 中番挺。
布局我就不詳細介紹了,無非就是HorizontalScrollView控件中嵌套一個子布局 LinearLayout襟衰。
代碼如下:
public static ?ArrayList<String> ??filePaths ; ? ?/ /圖片地址的集合
@Override
protected void ? onResume() {? ? ? //界面可見粪摘,且可與用戶交互
? ? ? super.onResume();
? ? ? ? ? ? ?if( filePaths!=null ){
? ? ? ? ? ? ? ? ? mLinearLayout.removeAllViews();
? ? ? ? ? ? ? ? ? mLinearLayout.setVisibility(View.VISIBLE);
? ? ? ? ? ? ? ? ? ?for (int ?i=0 ; i<= filePaths.size() ;i++){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ImageView imageView ?= ?new ?ImageView(this);
? ? ? ? ? ? ? ? ? ? ? ? ? ?LinearLayout.LayoutParams params=newLinearLayout.LayoutParams(200,200);
? ? ? ? ? ? ? ? ? ? ? ? ? ?params.rightMargin=10;
? ? ? ? ? ? ? ? ? ? ? ? ? ?params.leftMargin=10;
? ? ? ? ? ? ? ? ? ? ? ? ? imageView.setLayoutParams(params);
? ? ? ? ? ? ? ? ? ? ? ? ?if ?( ?i < ?filePaths.size() ) ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? File ? file ?= new ?File( filePaths.get(i) );
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if( ?file.exists() ){?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Bitmap bitmap= BitmapFactory.decodeFile(filePaths.get(i));
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? imageView.setImageBitmap(bitmap);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}else{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? imageView.setImageResource(R.mipmap.default_img); ? }
? ? ? ? ? ? ? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?imageView.setImageResource(R.mipmap.btn_add_img);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ? mLinearLayout.addView(imageView,i);
? ? ? ? ? ? ? ? ? ? ? ImageViewOnClick(imageView,i);? / / ? ImageView 的點擊事件
? ? ? ? ? ? ? ? ? ? ?}
}
}
上述代碼中 ,是根據 圖片路徑集合的長度來創(chuàng)建 ImageView 實例的苔悦,并添加到LinearLayout 中。默認添加一個圖片把介,用來點擊調用系統(tǒng)的拍照蟋座。當點擊圖片時拗踢,如不是默認圖片向臀,則跳轉到圖片詳情頁巢墅,否則調用系統(tǒng)拍照券膀。
圖片詳情頁使用的是 PhotoView,是一個比較常用的圖片開源庫蓄髓,可以根據手勢來縮放圖片雀监。
下面是調用系統(tǒng)拍照的代碼:
? ? ? ? Intent intent=new Intent( MediaStore.ACTION_IMAGE_CAPTURE);
? ? ? ? Uri uri=Uri.fromFile(newFile(mImgPath));
? ? ? ? intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
? ? ? ? intent.putExtra(MediaStore.Images.ImageColumns.ORIENTATION,0);
? ? ? ? startActivityForResult(intent,1001);
其中?mImgPath 是拍照圖片保存的路徑眨唬。需要自己手動生成。
然后就是 onActivityResult()方法啦匾竿,拍照后 圖片的內容就保存在 mImgPath 這個路徑之中。我們需要在這個方法中對 圖片進行一些必要的處理临庇。
處理的原因是,現(xiàn)在的手機像素非常高了昵慌,拍成的圖片一般都比較大,如果不對圖片進行處理斋攀,會很容易造成內存溢出,從而使你的應用崩潰侧蘸。在這里推薦一個圖片壓縮的第三方庫,Luban 壓縮讳癌,可以去研究下。
圖片的處理代碼如下:
Bitmap bitmap= ImageTools.convertToBitmap(mImgPath,800,800); // 轉換成圖片
Bitmap bitmapComp=ImageTools.comp(bitmap);//進行圖片壓縮
ImageTools.saveBitmap(bitmapComp,mImgPath);//保存圖片
if(bitmap!=null){
? ? ? ? filePaths.add(mImgPath);
}
這里代碼的基本思路就是逢艘,對拍照返回的路徑中的內容轉換成圖片骤菠,并對圖片進行壓縮處理埋虹,然后將圖片保存到拍照返回的路徑中娩怎,最后將路徑添加到集合中。