English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Implementación del efecto de ampliación de la imagen al arrastrar y deslizar en DragImageView de Android

DragImageView: arrastrar y deslizar la imagen para ampliar, primero veamos la imagen:

Las clases principales: heredan de RelativeLayout, y luego agregan ImageView dentro de RelativeLayout, modificando el tamaño de ImageView a través de eventos de Touch. Al calcular el scale, se asegura de que cuando el dedo se mueva hasta el fondo de la pantalla, la parte inferior de la imagen también alcance el fondo de la pantalla, y cuando el dedo se suelte, la imagen se recupera gradualmente.

package com.example.dragimagescale; 
import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.content.Context; 
import android.content.res.TypedArray; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Matrix; 
import android.graphics.PointF; 
import android.os.Handler; 
import android.os.Message; 
import android.util.AttributeSet; 
import android.util.DisplayMetrics; 
import android.util.Log; 
import android.view.MotionEvent; 
import android.view.WindowManager; 
import android.widget.ImageView; 
import android.widget.ImageView.ScaleType; 
import android.widget.RelativeLayout; 
public class DragScaleImageView extends RelativeLayout { 
 private String TAG = "DragScaleImageView"; 
 private static final int BACK_SCALE = 1010; 
 private Context mContext; 
 private AttributeSet attrs; 
 private int displayWidth = 0; 
 private int displayHeight = 0; 
 private int mImageId; 
 private Bitmap bmp; 
 private ImageView imageView; 
 /** ¿Está en estado de rebote? */ 
 private boolean isBacking = false; 
 /** Usado para registrar la posición de desplazamiento de la imagen arrastrada */ 
 private Matrix matrix = new Matrix(); 
 /** Usado para registrar la posición en el momento de arrastrar la imagen */ 
 private Matrix currentMatrix = new Matrix(); 
 private Matrix defaultMatrix = new Matrix(); 
 /** Ancho y alto de la imagen */ 
 private float imgHeight, imgWidth; 
 /** estado inicial */ 
 private int mode = 0; 
 /** modo de arrastrar fotos */ 
 private final int MODE_DRAG = 1; 
 private float scaleY = 0; 
 /** Usado para registrar la posición en el momento del inicio */ 
 private PointF startPoint = new PointF(); 
 /** Usado para registrar la posición Y en toda la pantalla en el momento del inicio */ 
 private float startRawY = 0; 
 float scale = 1; 
 private TouchEventListener touchEventListener = null; 
 private BackScaleListener backScaleListener = null; 
 public DragScaleImageView(Context context, AttributeSet attrs) { 
  super(context, attrs); 
  // TODO Auto-esqueleto de constructor generado 
  this.mContext = context; 
  this.attrs = attrs; 
  initView(); 
 } 
 public DragScaleImageView(Context context) { 
  super(context); 
  // TODO Auto-esqueleto de constructor generado 
  this.mContext = context; 
  initView(); 
 } 
 public DragScaleImageView(Activity activity, Bitmap resBitmap, int width, 
   int height) { 
  super(activity); 
 } 
 /** 
  * Inicializar la imagen 
  */ 
 private void initView() { 
  /* Obtener el tamaño de la resolución de la pantalla */ 
  DisplayMetrics dm = new DisplayMetrics(); 
  WindowManager mWm = (WindowManager) mContext 
    .getSystemService(Context.WINDOW_SERVICE); 
  mWm.getDefaultDisplay().getMetrics(dm); 
  displayWidth = dm.widthPixels; 
  displayHeight = dm.heightPixels; 
  TypedArray a = mContext.obtainStyledAttributes(attrs, 
    R.styleable.DragScaleImageView); 
  mImageId = a.getResourceId(R.styleable.DragScaleImageView_scale_image, 
    0); 
  a.recycle(); 
  if (null == bmp && mImageId != 0) { 
   bmp = BitmapFactory.decodeResource(getResources(), mImageId); 
   float scale = (float) displayWidth / (float) bmp.getWidth();// 1080/1800 
   matrix.postScale(scale, scale, 0, 0); 
   imgHeight = scale; * bmp.getHeight(); 
   imgWidth = scale; * bmp.getWidth(); 
  } else { 
   imgHeight = displayWidth; 
   imgWidth = displayWidth; 
  } 
  initImageView(); 
 } 
 private void initImageView() { 
  imageView = new ImageView(mContext); 
  imageView.setImageMatrix(matrix); 
  defaultMatrix.set(matrix); 
  Log.w(TAG, "imgWidth :" + imgWidth); 
  Log.w(TAG, "imgHeight :" + imgHeight); 
  RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( 
    (int) imgWidth, (int) imgHeight); 
  imageView.setLayoutParams(layoutParams); 
  imageView.setImageBitmap(bmp); 
  imageView.setScaleType(ScaleType.CENTER_CROP); 
  this.addView(imageView); 
 } 
 /** 
  * set the width and height of ImageView 
  * 
  * @param width 
  * @param height 
  */ 
 public void setImageWidthAndHeight(int width, int height) { 
  imgWidth = width; 
  imgHeight = height; 
  RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( 
    (int) imgWidth, (int) imgHeight); 
  imageView.setLayoutParams(layoutParams); 
 } 
 public boolean onTouchEvent(MotionEvent event) { 
  Log.w(TAG, "onTouchEvent :" + event.getAction()); 
  // When this View is placed inside a ScrollView, it may conflict with the parent control's Touch event, so the parent control is not available when touching the control area 
  if (event.getAction() == MotionEvent.ACTION_UP) { 
   getParent().requestDisallowInterceptTouchEvent(false); 
  } else { 
   getParent().requestDisallowInterceptTouchEvent(true);// true indicates that the parent class is not available; 
  } 
  switch (event.getAction() & MotionEvent.ACTION_MASK) { 
  // finger presses the screen 
  case MotionEvent.ACTION_DOWN: 
   if (isBacking) { 
    return super.onTouchEvent(event); 
   } 
   int[] location = new int[2]; 
   imageView.getLocationInWindow(location); 
   if (location[1] >= 0) { 
    mode = MODE_DRAG; 
    // register the current moving position of ImageView 
    currentMatrix.set(imageView.getImageMatrix()); 
    startPoint.set(event.getX(), event.getY()); 
    startRawY = event.getRawY(); 
    Log.w(TAG, "onTouchEvent startRawY:" + startRawY); 
   } 
   break; 
  // cuando el dedo se mueve en la pantalla, este evento se activará repetidamente 
  caso MotionEvent.ACTION_MOVE: 
   // arrastrar la imagen 
   if (mode == MODE_DRAG) { 
//    float dx = event.getX() - startPoint.x; // obtener la distancia de desplazamiento en el eje x 
    float dy = event.getY() - startPoint.y; // obtener la distancia de desplazamiento en el eje y 
    // mover en la posición antes de que se moviera 
    if (dy > 0) { 
     matrix.set(currentMatrix); 
     Log.w(TAG, "onTouchEvent dy:" + dy); 
     scale = ((dy / (displayHeight - startRawY) * (displayHeight - imgHeight)) + imgHeight) 
       / imgHeight; // obtener el factor de escala, cuando el dedo se mueve al fondo de la pantalla, la imagen también alcanza el fondo de la pantalla 
     Log.w(TAG, "onTouchEvent scale:" + scale); 
     scaleY = dy; 
     RelativeLayout.LayoutParams relativeLayout = new RelativeLayout.LayoutParams( 
       (int) (scale * imgWidth), (int) (scale * imgHeight)); 
     imageView.setLayoutParams(relativeLayout); 
     matrix.postScale(scale, scale, imgWidth / 2, 0); 
     imageView.setImageMatrix(matrix); 
    } 
   } 
   break; 
  // el dedo sale de la pantalla 
  caso MotionEvent.ACTION_UP: 
   // cuando el punto de contacto sale de la pantalla, la imagen se restaura 
   mHandler.sendEmptyMessage(BACK_SCALE); 
  caso MotionEvent.ACTION_POINTER_UP: 
   // cuando dos dedos se mueven, cancelar el desplazamiento de la imagen 
   mode = 0; 
   break; 
  } 
  // configuración del evento de escucha táctil 
  if (touchEventListener != null) { 
   touchEventListener.onTouchEvent(event); 
  } 
  return true; 
 } 
 /** gradual rebound */ 
 @SuppressLint("HandlerLeak") 
 private Handler mHandler = new Handler() { 
  @Override 
  public void handleMessage(Message msg) { 
   // TODO Auto-método de plantilla generado 
   switch (msg.what) { 
   caso BACK_SCALE: 
    scale = (scaleY / 2 + imgHeight) / (imgHeight);// obtener el factor de escala 
    if (scaleY > 0) { 
     isBacking = true; 
     matrix.set(currentMatrix); 
     RelativeLayout.LayoutParams relativeLayout = new RelativeLayout.LayoutParams( 
       (int) (scale * imgWidth), (int) (scale * imgHeight)); 
     imageView.setLayoutParams(relativeLayout); 
     matrix.postScale(scale, scale, imgWidth / 2, 0); 
     imageView.setImageMatrix(matrix); 
     scaleY = (float) (scaleY / 2 - 1); 
     mHandler.sendEmptyMessageDelayed(BACK_SCALE, 20);// gradual rebound 
    } else { 
     scaleY = 0; 
     RelativeLayout.LayoutParams relativeLayout = new RelativeLayout.LayoutParams( 
       (int) imgWidth, (int) imgHeight); 
     imageView.setLayoutParams(relativeLayout); 
     matrix.set(defaultMatrix); 
     imageView.setImageMatrix(matrix); 
     isBacking = false; 
    } 
    if (backScaleListener != null) { 
     backScaleListener.onBackScale(); 
    } 
    break; 
   default: 
    break; 
   } 
   super.handleMessage(msg); 
  } 
 }; 
 public void setTouchEventListener(TouchEventListener touchEventListener) { 
  this.touchEventListener = touchEventListener; 
 } 
 public void setBackScaleListener(BackScaleListener backScaleListener) { 
  this.backScaleListener = backScaleListener; 
 } 
 /** escucha de eventos de toque */ 
 public interface TouchEventListener { 
  public void onTouchEvent(MotionEvent event); 
 } 
 /** escucha de eventos de rebote */ 
 public interface BackScaleListener { 
  public void onBackScale(); 
 } 
} 

Activity llamada: }}

package com.example.dragimagescale; 
import com.example.dragimagescale.DragScaleImageView.BackScaleListener; 
import com.example.dragimagescale.DragScaleImageView.TouchEventListener; 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.MotionEvent; 
public class MainActivity extends Activity { 
 DragScaleImageView mDragScaleImageView; 
 @Override 
 protected void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.activity_main); 
  mDragScaleImageView = (DragScaleImageView) findViewById(R.id.dragScaleImageView); 
  /** definir el ancho y la altura de ImageView personalizado, si no se configura, se comprime según las dimensiones de la imagen hasta el ancho de la pantalla */ 
//  mDragScaleImageView.setImageWidthAndHeight(720, 300); 
  // escucha de eventos de toque 
  mDragScaleImageView.setTouchEventListener(new TouchEventListener() { 
   @Override 
   public void onTouchEvent(MotionEvent event) { 
    // TODO Auto-método de plantilla generado 
    // hacer algo aquí 
   } 
  ); 
  // escucha de eventos de rebote 
  mDragScaleImageView.setBackScaleListener(new BackScaleListener() { 
   @Override 
   public void onBackScale() { 
    // TODO Auto-método de plantilla generado 
    // hacer algo aquí 
   } 
  ); 
 } 
} 

Archivo de diseño XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android 
 xmlns:tools="http://schemas.android.com/tools 
 xmlns:dragscaleimageview="http://schemas.android.com/apk/res/com.example.dragimagescale 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:background="#ffffff" > 
 <com.example.dragimagescale.DragScaleImageView 
  android:id="@"+id/dragScaleImageView" 
  android:layout_width="match_parent"   
  android:layout_height="wrap_content" 
  dragscaleimageview:scale_image="@drawable/image" 
  > 
 </com.example.dragimagescale.DragScaleImageView> 
</RelativeLayout> 

Descarga:Código fuente

Esto es todo el contenido de este artículo, esperamos que sea útil para su aprendizaje y que todos nos apoyen en el tutorial de clamor.

Declaración: Este artículo se ha redactado en línea, es propiedad del autor original, el contenido ha sido contribuido y subido por los usuarios de Internet, este sitio web no posee los derechos de propiedad, no ha sido editado por humanos y no asume responsabilidad por las responsabilidades legales relacionadas. Si encuentra contenido sospechoso de infracción de derechos de autor, le invitamos a enviar un correo electrónico a: notice#w3Declaración: El contenido de este artículo se ha obtenido de la red, es propiedad del autor original, el contenido ha sido contribuido y subido por los usuarios de Internet, este sitio web no posee los derechos de propiedad, no ha sido editado por humanos y no asume responsabilidad por las responsabilidades legales relacionadas. Si encuentra contenido sospechoso de infracción de derechos de autor, le invitamos a enviar un correo electrónico a: notice#w

Te gustará