高仿新浪點選圖片放大(可以拖動,動態縮小放大,以及再次點選圖片消失和儲存圖片的功能)
阿新 • • 發佈:2019-02-02
有圖有真相:
最近在做專案的時候用到了點選圖片放大效果,於是就開始實現,本以為挺簡單的,實現起來還是遇到不少的小問題啊:
第一:只實現點選圖片放大,再次點選消失,這個好實現;
第二:只實現圖片可以拖動,而且可以動態縮小放大,這個也好實現;
第三:第一 和第二同步實現就出現問題了:
具體的問題是:
(1)setOnClickListener 和 setOnTouchListener 同時設定的時候,若是setOnTouchListener的返回值為true,則不會再執行setOnClickListener ;若是返回為false,則會執行setOnClickListener
(2)將setOnTouchListener的返回值設為false之後,執行專案,圖片縮小放大之後會直接消失,也就是直接執行了setOnClickListener ,但是專案的要求是,圖片移動了或者放大縮小了,依舊顯示圖片,只有點選的時候才會使圖片消失,我於是就用一個變數進行控制手指點選螢幕之後的大小小於1的時候才算是點選了圖片,從而讓圖片消失,具體不多說了,看圖和程式碼:
大家若是有更好的實現方法,請給留個連結,大家互相學習一下!public class ImageToFullScreenActivity extends Activity implements OnClickListener { private String mImageUrl; private ImageWorker mImageWorker; private int mImageWidth; private int mImageHeight; private ImageView mFullImageView; private LinearLayout mImageLayout; private ImageView mSaveImage; private Boolean isShutDownPic = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.image_to_full_screen); mImageUrl = getIntent().getStringExtra("imageUrl"); init(); } private void init() { mImageLayout = (LinearLayout) findViewById(R.id.image_layout); mFullImageView = (ImageView) findViewById(R.id.full_image); mSaveImage = (ImageView) findViewById(R.id.save_image); mSaveImage.setOnClickListener(this); mImageLayout.setOnClickListener(this); mFullImageView.setOnClickListener(this); mFullImageView.setOnTouchListener(new TouchListener()); WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(outMetrics); mImageWidth = (int) (outMetrics.widthPixels * 1.0d); mImageHeight = mImageWidth; ImageCacheParams cacheParams = new ImageCacheParams(); cacheParams.loadingResId = R.drawable.image_full_screen; cacheParams.memCacheSize = ImageCache.DEFAULT_MEM_CACHE_SIZE_BIG; cacheParams.reqWidth = mImageWidth; cacheParams.reqHeight = mImageHeight; mImageWorker = new ImageWorker(this, (HealthApplication) getApplication()); mImageWorker.addParams(cacheParams); mImageWorker.loadBitmap(mImageUrl, mFullImageView); LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); mFullImageView.setLayoutParams(params); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.save_image: SaveImageToSysAlbum(); break; case R.id.image_layout: if(isShutDownPic){ ImageToFullScreenActivity.this.finish(); } isShutDownPic = true; break; case R.id.full_image: if(isShutDownPic){ ImageToFullScreenActivity.this.finish(); } isShutDownPic = true; break; default: break; } } /** * 將ImageView中的圖片儲存到系統相簿 */ private void SaveImageToSysAlbum() { if (FileUtil.isSdCardExist()) { BitmapDrawable bmpDrawable = (BitmapDrawable) mFullImageView .getDrawable(); Bitmap bmp = bmpDrawable.getBitmap(); if (bmp != null) { try { /* * ContentResolver cr = getContentResolver(); String url = * MediaStore.Images.Media.insertImage(cr, bmp, * String.valueOf(System.currentTimeMillis()), ""); */ File tempFile = new File(Environment .getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM).getPath() + "/" + String.valueOf(System.currentTimeMillis()) + ".png"); if (tempFile.exists()) { tempFile.delete(); } try { tempFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } FileOutputStream fOut = null; try { fOut = new FileOutputStream(tempFile); } catch (FileNotFoundException e) { e.printStackTrace(); } bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut); try { fOut.flush(); fOut.close(); } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } Toast.makeText(this, getString(R.string.save_succ), Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } } else { Toast.makeText(this, getString(R.string.no_iamge_save_fail), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(this, getString(R.string.no_sdcard_save_fail), Toast.LENGTH_SHORT).show(); } String release = android.os.Build.VERSION.RELEASE; String tempID = release.substring(0, 3); if (Double.parseDouble(tempID) >= 4.4) {// 安卓4.4以上版本的時候使用這個,以下的使用else語句裡面的 MediaScannerConnection.scanFile( this, new String[] { Environment .getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM).getPath() + "/" }, null, null); } else { sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); MediaScannerConnection.scanFile( this, new String[] { Environment .getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM).getPath() + "/" }, null, null); } } private class TouchListener implements OnTouchListener { private PointF startPoint = new PointF(); private Matrix matrix = new Matrix(); private Matrix currentMaritx = new Matrix(); private int mode = 0; // 用於標記模式 private static final int DRAG = 1; // 拖動 private static final int ZOOM = 2; // 放大 private float startDis = 0; private PointF midPoint; // 中心點 @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: mode = DRAG; // 拖拽 currentMaritx.set(mFullImageView.getImageMatrix()); // 記錄ImageView當前移動位置 startPoint.set(event.getX(), event.getY()); // 開始點 break; case MotionEvent.ACTION_MOVE:// 移動事件 float tempX = event.getX() - startPoint.x; float tempY = event.getY() - startPoint.y; /** * 控制移動小於1.0的情況下,視為沒有移動,執行點選事件 */ if(Math.abs(tempX) < 1.0 && Math.abs(tempY) < 1.0){ isShutDownPic = true; }else { isShutDownPic = false; } mFullImageView.setScaleType(ImageView.ScaleType.MATRIX); if (mode == DRAG) { // 圖片拖動事件 float dx = event.getX() - startPoint.x; // x軸移動距離 float dy = event.getY() - startPoint.y; matrix.set(currentMaritx); // 在當前的位置基礎上移動 matrix.postTranslate(dx, dy); } else if (mode == ZOOM) { // 圖片放大事件 float endDis = distance(event); // 結束距離 if (endDis > 10f) { float scale = endDis / startDis; // 放大倍數 matrix.set(currentMaritx); matrix.postScale(scale, scale, midPoint.x, midPoint.y); } } break; case MotionEvent.ACTION_UP: mode = 0; break; // 有手指離開螢幕,但螢幕還有觸點(手指) case MotionEvent.ACTION_POINTER_UP: mode = 0; break; // 當螢幕上已經有觸點(手指),再有一個手指壓下螢幕 case MotionEvent.ACTION_POINTER_DOWN: mode = ZOOM; startDis = distance(event); if (startDis > 10f) { // 避免手指上有兩個 midPoint = mid(event); currentMaritx.set(mFullImageView.getImageMatrix()); // 記錄當前的縮放倍數 } break; } // 顯示縮放後的圖片 mFullImageView.setImageMatrix(matrix); return false; } } /** * 計算兩點之間的距離 * * @param event * @return */ public static float distance(MotionEvent event) { float dx = event.getX(1) - event.getX(0); float dy = event.getY(1) - event.getY(0); return FloatMath.sqrt(dx * dx + dy * dy); } /** * 計算兩點之間的中間點 * * @param event * @return */ public static PointF mid(MotionEvent event) { float midX = (event.getX(1) + event.getX(0)) / 2; float midY = (event.getY(1) + event.getY(0)) / 2; return new PointF(midX, midY); } }