實現(xiàn)方法:點擊圖片時,把圖片url傳到另一個activity中實現(xiàn)放大拖動,
圖片點擊事件觸發(fā):
Intent intent = new Intent();
intent.setClass(mContext, PictureActivity.class);
intent.putExtra(“url”,R.drawable.ic_logo);
mContext.startActivity(intent);
然后創(chuàng)建一個activity的內(nèi)容如下:
public class PictureActivity extends AppCompatActivity {
private ZoomImageView zoomView;
private GestureDetector gestureDetector;
private LinearLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_picture_preview);
zoomView = (ZoomImageView) findViewById(R.id.zoom_view);
zoomView.getActivity(PicturePreviewActivity.this);
layout = (LinearLayout) this.findViewById(R.id.layout_picture_preview);
//這里把intent收到的資源文件下的圖片轉(zhuǎn)成bitmap。
Bitmap url = BitmapFactory.decodeResource(getResources(),
getIntent().getIntExtra("url", 0), null);
layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PicturePreviewActivity.this.finish();
}
});
//若圖片模糊,根據(jù)原圖比例調(diào)整這里的寬高即可
zoomView.setImageBitmap(zoomBitmap(url, 4080,
1920));
gestureDetector = new GestureDetector(this,
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
float x = e2.getX() - e1.getX();
if (x > 0) {
prePicture();
} else if (x < 0) {
nextPicture();
}
return true;
}
});
}
protected void nextPicture() {
// TODO Auto-generated method stub
}
protected void prePicture() {
// TODO Auto-generated method stub
}
@Override
public void onResume() {
super.onResume();
// recycle();
}
public void recycle() {
if (zoomView != null && zoomView.getDrawable() != null) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) zoomView
.getDrawable();
if (bitmapDrawable != null && bitmapDrawable.getBitmap() != null
&& !bitmapDrawable.getBitmap().isRecycled()) {
bitmapDrawable.getBitmap().recycle();
}
}
}
public Bitmap getBitMapFromUrl(String url) {
Bitmap bitmap = null;
URL u = null;
HttpURLConnection conn = null;
InputStream is = null;
try {
u = new URL(url);
conn = (HttpURLConnection) u.openConnection();
is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
}
return bitmap;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
/**
* Resize the bitmap
*
* @param bitmap
* @param width
* @param height
* @return
*/
public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
if (bitmap == null)
return bitmap;
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) width / w);
float scaleHeight = ((float) height / h);
if (scaleWidth < scaleHeight) {
matrix.postScale(scaleWidth, scaleWidth);
} else {
matrix.postScale(scaleHeight, scaleHeight);
}
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
return newbmp;
}
public static boolean checkSDCardAvailable() {
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
public void closeActivity() {
this.finish();
}
xml中代碼
<com.hekang.EM.utils.ZoomImageView
android:id=“@+id/zoom_view”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”/>
自定義ZoomImageView類全部代碼:
@SuppressLint(“AppCompatCustomView”)
public class ZoomImageView extends ImageView implements ScaleGestureDetector.OnScaleGestureListener,
View.OnTouchListener, ViewTreeObserver.OnGlobalLayoutListener
{
private static final String TAG = ZoomImageView.class.getSimpleName();
public static final float SCALE_MAX = 4.0f;
private static final float SCALE_MID = 2.0f;文章來源:http://www.zghlxwxcb.cn/news/detail-512205.html
/**
* 初始化時的縮放比例,如果圖片寬或高大于屏幕,此值將小于0
*/
private float initScale = 1.0f;
private boolean once = true;
/**
* 用于存放矩陣的9個值
*/
private final float[] matrixValues = new float[9];
/**
* 縮放的手勢檢測
*/
private ScaleGestureDetector mScaleGestureDetector = null;
private final Matrix mScaleMatrix = new Matrix();
/**
* 用于雙擊檢測
*/
private GestureDetector mGestureDetector;
private boolean isAutoScale;
private int mTouchSlop;
private float mLastX;
private float mLastY;
private boolean isCanDrag;
private int lastPointerCount;
private boolean isCheckTopAndBottom = true;
private boolean isCheckLeftAndRight = true;
private PicturePreviewActivity activity;
public void getActivity(PicturePreviewActivity activity) {
this.activity = activity;
}
public ZoomImageView(Context context) {
this(context, null);
}
public ZoomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
super.setScaleType(ScaleType.MATRIX);
mGestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDoubleTap(MotionEvent e) {
if (isAutoScale == true)
return true;
float x = e.getX();
float y = e.getY();
Log.e("DoubleTap", getScale() + " , " + initScale);
if (getScale() < SCALE_MID) {
ZoomImageView.this.postDelayed(
new AutoScaleRunnable(SCALE_MID, x, y), 16);
isAutoScale = true;
} else if (getScale() >= SCALE_MID
&& getScale() < SCALE_MAX) {
ZoomImageView.this.postDelayed(
new AutoScaleRunnable(SCALE_MAX, x, y), 16);
isAutoScale = true;
} else {
ZoomImageView.this.postDelayed(
new AutoScaleRunnable(initScale, x, y), 16);
isAutoScale = true;
}
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.i(TAG, "single");
activity.closeActivity();
return true;
}
});
mScaleGestureDetector = new ScaleGestureDetector(context, this);
this.setOnTouchListener(this);
}
/**
* 自動縮放的任務(wù)
*
* @author zhy
*/
private class AutoScaleRunnable implements Runnable {
static final float BIGGER = 1.07f;
static final float SMALLER = 0.93f;
private float mTargetScale;
private float tmpScale;
/**
* 縮放的中心
*/
private float x;
private float y;
/**
* 傳入目標(biāo)縮放值,根據(jù)目標(biāo)值與當(dāng)前值,判斷應(yīng)該放大還是縮小
*
* @param targetScale
*/
public AutoScaleRunnable(float targetScale, float x, float y) {
this.mTargetScale = targetScale;
this.x = x;
this.y = y;
if (getScale() < mTargetScale) {
tmpScale = BIGGER;
} else {
tmpScale = SMALLER;
}
}
@Override
public void run() {
// 進(jìn)行縮放
mScaleMatrix.postScale(tmpScale, tmpScale, x, y);
checkBorderAndCenterWhenScale();
setImageMatrix(mScaleMatrix);
final float currentScale = getScale();
// 如果值在合法范圍內(nèi),繼續(xù)縮放
if (((tmpScale > 1f) && (currentScale < mTargetScale))
|| ((tmpScale < 1f) && (mTargetScale < currentScale))) {
ZoomImageView.this.postDelayed(this, 16);
} else
// 設(shè)置為目標(biāo)的縮放比例
{
final float deltaScale = mTargetScale / currentScale;
mScaleMatrix.postScale(deltaScale, deltaScale, x, y);
checkBorderAndCenterWhenScale();
setImageMatrix(mScaleMatrix);
isAutoScale = false;
}
}
}
@SuppressLint("NewApi")
@Override
public boolean onScale(ScaleGestureDetector detector) {
float scale = getScale();
float scaleFactor = detector.getScaleFactor();
if (getDrawable() == null)
return true;
/**
* 縮放的范圍控制
*/
if ((scale < SCALE_MAX && scaleFactor > 1.0f)
|| (scale > initScale && scaleFactor < 1.0f)) {
/**
* 最大值最小值判斷
*/
if (scaleFactor * scale < initScale) {
scaleFactor = initScale / scale;
}
if (scaleFactor * scale > SCALE_MAX) {
scaleFactor = SCALE_MAX / scale;
}
/**
* 設(shè)置縮放比例
*/
mScaleMatrix.postScale(scaleFactor, scaleFactor,
detector.getFocusX(), detector.getFocusY());
checkBorderAndCenterWhenScale();
setImageMatrix(mScaleMatrix);
}
return true;
}
/**
* 在縮放時,進(jìn)行圖片顯示范圍的控制
*/
private void checkBorderAndCenterWhenScale() {
RectF rect = getMatrixRectF();
float deltaX = 0;
float deltaY = 0;
int width = getWidth();
int height = getHeight();
// 如果寬或高大于屏幕,則控制范圍
if (rect.width() >= width) {
if (rect.left > 0) {
deltaX = -rect.left;
}
if (rect.right < width) {
deltaX = width - rect.right;
}
}
if (rect.height() >= height) {
if (rect.top > 0) {
deltaY = -rect.top;
}
if (rect.bottom < height) {
deltaY = height - rect.bottom;
}
}
// 如果寬或高小于屏幕,則讓其居中
if (rect.width() < width) {
deltaX = width * 0.5f - rect.right + 0.5f * rect.width();
}
if (rect.height() < height) {
deltaY = height * 0.5f - rect.bottom + 0.5f * rect.height();
}
Log.e(TAG, "deltaX = " + deltaX + " , deltaY = " + deltaY);
mScaleMatrix.postTranslate(deltaX, deltaY);
}
/**
* 根據(jù)當(dāng)前圖片的Matrix獲得圖片的范圍
*
* @return
*/
private RectF getMatrixRectF() {
Matrix matrix = mScaleMatrix;
RectF rect = new RectF();
Drawable d = getDrawable();
if (null != d) {
rect.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
matrix.mapRect(rect);
}
return rect;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mGestureDetector.onTouchEvent(event))
return true;
mScaleGestureDetector.onTouchEvent(event);
float x = 0, y = 0;
// 拿到觸摸點的個數(shù)
final int pointerCount = event.getPointerCount();
// 得到多個觸摸點的x與y均值
for (int i = 0; i < pointerCount; i++) {
x += event.getX(i);
y += event.getY(i);
}
x = x / pointerCount;
y = y / pointerCount;
/**
* 每當(dāng)觸摸點發(fā)生變化時,重置mLasX , mLastY
*/
if (pointerCount != lastPointerCount) {
isCanDrag = false;
mLastX = x;
mLastY = y;
}
lastPointerCount = pointerCount;
RectF rectF = getMatrixRectF();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (rectF.width() > getWidth() || rectF.height() > getHeight()) {
getParent().requestDisallowInterceptTouchEvent(true);
}
break;
case MotionEvent.ACTION_MOVE:
if (rectF.width() > getWidth() || rectF.height() > getHeight()) {
getParent().requestDisallowInterceptTouchEvent(true);
}
Log.e(TAG, "ACTION_MOVE");
float dx = x - mLastX;
float dy = y - mLastY;
if (!isCanDrag) {
isCanDrag = isCanDrag(dx, dy);
}
if (isCanDrag) {
if (getDrawable() != null) {
// if (getMatrixRectF().left == 0 && dx > 0)
// {
// getParent().requestDisallowInterceptTouchEvent(false);
// }
//
// if (getMatrixRectF().right == getWidth() && dx < 0)
// {
// getParent().requestDisallowInterceptTouchEvent(false);
// }
isCheckLeftAndRight = isCheckTopAndBottom = true;
// 如果寬度小于屏幕寬度,則禁止左右移動
if (rectF.width() < getWidth()) {
dx = 0;
isCheckLeftAndRight = false;
}
// 如果高度小雨屏幕高度,則禁止上下移動
if (rectF.height() < getHeight()) {
dy = 0;
isCheckTopAndBottom = false;
}
mScaleMatrix.postTranslate(dx, dy);
checkMatrixBounds();
setImageMatrix(mScaleMatrix);
}
}
mLastX = x;
mLastY = y;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
Log.e(TAG, "ACTION_UP");
lastPointerCount = 0;
break;
}
return true;
}
/**
* 獲得當(dāng)前的縮放比例
*
* @return
*/
public final float getScale() {
mScaleMatrix.getValues(matrixValues);
return matrixValues[Matrix.MSCALE_X];
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
getViewTreeObserver().addOnGlobalLayoutListener(this);
}
@SuppressWarnings("deprecation")
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
@Override
public void onGlobalLayout() {
if (once) {
Drawable d = getDrawable();
if (d == null)
return;
Log.e(TAG, d.getIntrinsicWidth() + " , " + d.getIntrinsicHeight());
int width = getWidth();
int height = getHeight();
// 拿到圖片的寬和高
int dw = d.getIntrinsicWidth();
int dh = d.getIntrinsicHeight();
float scale = 1.0f;
// 如果圖片的寬或者高大于屏幕,則縮放至屏幕的寬或者高
if (dw > width && dh <= height) {
scale = width * 1.0f / dw;
}
if (dh > height && dw <= width) {
scale = height * 1.0f / dh;
}
// 如果寬和高都大于屏幕,則讓其按按比例適應(yīng)屏幕大小
if (dw > width && dh > height) {
scale = Math.min(width * 1.0f / dw, height * 1.0f / dh);
}
initScale = scale;
Log.e(TAG, "initScale = " + initScale);
mScaleMatrix.postTranslate((width - dw) / 2, (height - dh) / 2);
mScaleMatrix.postScale(scale, scale, getWidth() / 2,
getHeight() / 2);
// 圖片移動至屏幕中心
setImageMatrix(mScaleMatrix);
once = false;
}
}
/**
* 移動時,進(jìn)行邊界判斷,主要判斷寬或高大于屏幕的
*/
private void checkMatrixBounds() {
RectF rect = getMatrixRectF();
float deltaX = 0, deltaY = 0;
final float viewWidth = getWidth();
final float viewHeight = getHeight();
// 判斷移動或縮放后,圖片顯示是否超出屏幕邊界
if (rect.top > 0 && isCheckTopAndBottom) {
deltaY = -rect.top;
}
if (rect.bottom < viewHeight && isCheckTopAndBottom) {
deltaY = viewHeight - rect.bottom;
}
if (rect.left > 0 && isCheckLeftAndRight) {
deltaX = -rect.left;
}
if (rect.right < viewWidth && isCheckLeftAndRight) {
deltaX = viewWidth - rect.right;
}
mScaleMatrix.postTranslate(deltaX, deltaY);
}
/**
* 是否是推動行為
*
* @param dx
* @param dy
* @return
*/
private boolean isCanDrag(float dx, float dy) {
return Math.sqrt((dx * dx) + (dy * dy)) >= mTouchSlop;
}
}文章來源地址http://www.zghlxwxcb.cn/news/detail-512205.html
到了這里,關(guān)于Android 點擊圖片,放大查看,實現(xiàn)縮放拖動等功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!