1. 程式人生 > 程式設計 >Android實現圖片點選放大

Android實現圖片點選放大

本文例項為大家分享了Android實現圖片點選放大的具體程式碼,供大家參考,具體內容如下

在我的專案中,有點選圖片banner後放大瀏覽的功能。我的做法就是建立一個專門的圖片顯示Activity,佈局裡面用ViewPage,這樣就能控制圖片的左右滑動,並且控制首先顯示第幾張圖片。
功能是ok的,顯示也是正常的。但我花費了好幾天的時間來實現、完善這個功能。

ShowMoreImageActivity

/**
 * 圖片放大
 */
public class ShowMoreImageActivity extends BaseActivity {

 @FindId(R.id.vp)
 private ViewPager vp;
 @FindId(R.id.ll_point)
 private LinearLayout ll_point;

 private List<String> imgs;
 @FindId(R.id.btn_save)
 private ImageView btn_save;

 private int index;

 public static int type;
 private Activity activity;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_show_more_image);
  initViews();
 activity = this;
 }

 private void initViews() {
  AutoFindId.findId(context);

  imgs = (ArrayList<String>) getIntent().getSerializableExtra("img");
  index = getIntent().getIntExtra("index",0);

  type = getIntent().getIntExtra("type",0);
  vp.setAdapter(new MoreImgPagerAdapter(context,imgs));


  vp.addOnPageChangeListener(new OnPageChangeListener() {
   @Override
   public void onPageSelected(int arg0) {
    index = arg0;
    setUpPoint(imgs.size(),arg0);
   }

   @Override
   public void onPageScrolled(int arg0,float arg1,int arg2) {
   }

   @Override
   public void onPageScrollStateChanged(int arg0) {
   }
  });
  setUpPoint(imgs.size(),0);

  vp.setCurrentItem(index);
 }

 protected void downLoad(final String urls) {
  String[] split = urls.split("\\?");
  final String url = split[0];
  if (url.startsWith("file")) {
   G.toast(context,"此為本地圖片,不用下載,路徑為" + url.replace("file://",""));
   return;
  }

  if (OKHttpUtils.isNetworkAvailable(context)) {
   G.showPd(context);
   TDUtils.execute(new Runnable() {
    @Override
    public void run() {
     try {
      File file = new File(C.getDownloadPath());
      if (!file.exists()) {
       file.mkdir();
      }
      File jpg = new File(C.getDownloadPath() + G.urlToFileName(url));
      // 如果已經存在則不需要下載
      if (jpg != null && jpg.exists()) {
       G.dismissProgressDialogInThread();

       G.toastInThread(context,"該檔案已被下載到" + jpg.getParent() + context.getResources().getString(R.string.xia));
       return;
      }
      // 先從快取中查詢
      File tmpFile = NetAide.getBitmapUtils().getBitmapFileFromDiskCache(url);
      if (tmpFile != null && tmpFile.exists()) {
       G.look("---從快取中查詢到圖片----");
       Bitmap bm = BitmapFactory.decodeFile(tmpFile.getAbsolutePath());

       FileOutputStream fos = new FileOutputStream(jpg);
       bm.compress(CompressFormat.JPEG,100,fos);
       fos.close();
       G.dismissProgressDialogInThread();

       // 通知相簿更新
       C.noticeImageRefresh(context,jpg);

       G.toastInThread(context,context.getResources().getString(R.string.downLoadUrl)
         + jpg.getParent() + context.getResources().getString(R.string.xia));
       return;
      }

      // 從網路上下載儲存
      Bitmap bm = BitmapFactory.decodeStream(new URL(url).openStream());

      FileOutputStream fos = new FileOutputStream(jpg);
      bm.compress(CompressFormat.JPEG,fos);
      fos.close();
      G.dismissProgressDialogInThread();

      // 通知相簿更新
      C.noticeImageRefresh(context,jpg);
      G.toastInThread(context,"你現在可以在相簿中檢視該圖片了");

     } catch (Exception e) {
      e.printStackTrace();
      G.dismissProgressDialogInThread();

      G.toastInThread(context,context.getResources().getString(R.string.downLoadFail));

      File jpg = new File(C.getDownloadPath() + G.urlToFileName(url));
      if (jpg != null && jpg.exists()) {
       jpg.delete();
      }
     }
    }
   });
  }

 }

 private void setUpPoint(int size,int choose) {
  ll_point.removeAllViews();
  if (size <= 1) {
   return;
  }

  for (int i = 0; i < size; i++) {
   ImageView point = new ImageView(context);
   point.setLayoutParams(new LinearLayout.LayoutParams(DensityUtil.dip2px(context,15),-2));
   point.setScaleType(ScaleType.FIT_CENTER);
   if (i == choose) {
    point.setImageResource(R.drawable.white_choosed);
   } else {
    point.setImageResource(R.drawable.white_no_choosed);
   }
   ll_point.addView(point);
  }
 }

 public void doClcik(View view) {
  switch (view.getId()){
 case R.id.btn_save:
    PermissionUtils permissionUtils = new PermissionUtils();
    permissionUtils.setPermission(this,"儲存","儲存圖片",new PermissionUtils.AfterPermission() {
     @Override
     public void doNext() {
      downLoad(imgs.get(index));
     }
    },Manifest.permission.WRITE_EXTERNAL_STORAGE);
 break;
 }
 }
}

對應佈局:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@android:color/black"
 android:orientation="vertical">

 <androidx.viewpager.widget.ViewPager
  android:id="@+id/vp"
  android:layout_width="match_parent"
  android:layout_height="match_parent" />

 <LinearLayout
  android:layout_width="match_parent"
  android:layout_height="40dp"
  android:layout_marginTop="25dp">

  <LinearLayout
   android:layout_width="50dp"
   android:layout_height="match_parent"
   android:onClick="onFinish">

   <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:layout_marginLeft="10dp"
    android:background="@drawable/nav_back" />

  </LinearLayout>

  <View
   android:layout_width="0dp"
   android:layout_height="0dp"
   android:layout_weight="1" />

  <ImageView
   android:id="@+id/btn_save"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_gravity="center_vertical"
   android:layout_marginRight="10dp"
   android:onClick="doClcik"
   android:src="@drawable/download_img" />
 </LinearLayout>

 <LinearLayout
  android:id="@+id/ll_point"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_gravity="bottom"
  android:layout_marginBottom="40dp"
  android:gravity="center"
  android:orientation="horizontal"/>

</FrameLayout>

MoreImgPagerAdapter

public class MoreImgPagerAdapter extends PagerAdapter {

 private Context context;
 private List<String> images;

 private SparseArray<SoftReference<View>> ivs;

 public MoreImgPagerAdapter(Context context,List<String> images) {
 this.context = context;
 this.images = images;
 ivs = new SparseArray<SoftReference<View>>();
 }

 @Override
 public int getCount() {
 return images.size();
 }

 @Override
 public void destroyItem(ViewGroup arg0,int arg1,Object arg2) {
 SoftReference<View> reference = ivs.get(arg1);
 if (reference != null && reference.get() != null) {
 arg0.removeView(reference.get());
 }
 }

 @Override
 public Object instantiateItem(ViewGroup arg0,final int arg1) {
 SoftReference<View> reference = ivs.get(arg1);
 if (reference == null || reference.get() == null) {
 View v = LayoutInflater.from(context).inflate(R.layout.item_show_more_image,null);
 reference = new SoftReference<View>(v);
 ivs.put(arg1,reference);
 }

 View v = reference.get();

 final ViewHolder holder = new ViewHolder(v);
 Glide.with(context).asBitmap().load(images.get(arg1)).into(holder.image);
 arg0.addView(v);

 return v;

 }



 @Override
 public boolean isViewFromObject(View arg0,Object arg1) {
 return arg0.equals(arg1);
 }

 class ViewHolder {
 @FindId(R.id.image)
 private ImageView image;

 @FindId(R.id.rl_percent)
 private RelativeLayout rl_percent;
 @FindId(R.id.tv_percent)
 private TextView tv_percent;
 @FindId(R.id.iv_top)
 private ImageView iv_top;
 
 public ViewHolder(View v) {
 AutoFindId.findIdByView(this,v);
 }
 }
}

對應佈局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@android:color/black"
 android:orientation="vertical" >

 <FrameLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:layout_marginBottom="50dp"
  android:layout_marginTop="70dp" >

  <ImageView
   android:layout_gravity="center"
   android:id="@+id/image"
   android:layout_width="match_parent"
   android:layout_height="match_parent" />

  <ImageView
   android:id="@+id/iv_top"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_gravity="top|right"
   android:visibility="gone"
   android:background="@drawable/shuiyin" />
 </FrameLayout>

 <RelativeLayout
  android:visibility="gone"
  android:id="@+id/rl_percent"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_centerInParent="true" >

  <ProgressBar
   android:layout_width="40dp"
   android:layout_height="40dp" />

  <TextView
   android:id="@+id/tv_percent"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:textColor="@android:color/white"
   android:textSize="12sp" />
 </RelativeLayout>

</RelativeLayout>

上面都是次要的,因為我發現了一個更為簡便的輪子。

github地址

在我的專案中,我只需要兩步就完成了此功能。

第一步:

// 檢視大圖
implementation 'com.github.SherlockGougou:BigImageViewPager:v4_6.1.1'

第二步:

在點選圖片事件那裡呼叫:

ImagePreview
  .getInstance()
  // 上下文,必須是activity,不需要擔心記憶體洩漏,本框架已經處理好;
  .setContext(context)
  // 設定從第幾張開始看(索引從0開始)
  .setIndex(position)
  // 有三種設定資料集合的方式,根據自己的需求進行三選一:
  // 1:第一步生成的imageInfo List
  //.setImageInfoList(imageInfoList)
  // 2:直接傳url List
  .setImageList(imageList)
  // 3:只有一張圖片的情況,可以直接傳入這張圖片的url
  //.setImage(String image)
  // 開啟預覽
 .start();

就這樣完成了圖片放大瀏覽、下載的功能,在這裡記錄下。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。