Android图片左右切换和拖动大小

Android图片左右切换和拖动大小

Android观看图片时,左右滑动实现照片切换,多手势实现照片的扩大和缩小。Android中使用ImageView来展示图片,对其进行监听,就可以实现图片的各种变换。

ImageView imageView;
imageView = (ImageView)findViewById(R.id.someId);
imageView.setOnTouchListener(new OnTouchListener()
{       
    public boolean onTouch(View v, MotionEvent event)
    {
        //监听代码
        switch (event.getAction() & MotionEvent.ACTION_MASK) 
        {
            ...
        } 
    }
}   

上面代码就是为ImageView添加一个监听端口,实现多手势监听。如果没有MotionEvent.ACTION_MASK那么只能识别单手指动作。

下面代码,根据图片URL从网上加载图片,展示出来,可以滑动切换、多手势改变大小贴出来。

public class ImageActivity extends Activity
{
    private List<String> imageUrlList; //图片url列表
    private TextView view;
    private ImageView imageView;
    private String url;
    //当前是第几个图片
    private int index;
    private Bitmap bitmap;

    Matrix matrix = new Matrix(); 
    Matrix savedMatrix = new Matrix(); 
    PointF start = new PointF(); 
    PointF mid = new PointF(); 
    float  oldDist; 

   //定义三种状态,空、拖动、改变大小
   static final int NONE = 0; 
   static final int DRAG = 1; 
   static final int ZOOM = 2; 
   //当前触发的事件
   int mode = NONE; 
   //记录是否是ZOOM模式,只有ZOOM模式才会有drag动作
   int previousMode = NONE;

   //android规定,主线程不能去加载http请求,要用子线程,handler实现线程之间的通信
   private Handler handler = new Handler()
   {
        public void handleMessage(Message msg)
        {
            Bundle bundle = msg.getData();
            if("ok".equals(bundle.getString("status")))
            {
                setProgressBarIndeterminateVisibility(false);
                matrix = new Matrix();
                imageView.setImageBitmap(bitmap);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        //获取标题进度条,添加一个进度条,当子线程正在加载的时候,提醒用户
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_image);
        index = 0;

        //获取上一个页面传过来的信息
        Intent intent = this.getIntent();
        Bundle bundle = intent.getBundleExtra("data");
        url = bundle.getString("url");

        view = (TextView)findViewById(R.id.imageUrl);
        imageView = (ImageView)findViewById(R.id.image);
        //添加loading界面
        setProgressBarIndeterminateVisibility(true);
        new Thread(imagesRunnable).start();
        new Thread(imageResourceRunnable).start();

        //为imageView添加监听事件
        imageView.setOnTouchListener(new OnTouchListener()
        {       
            public boolean onTouch(View v, MotionEvent event)
            {               
                switch (event.getAction() & MotionEvent.ACTION_MASK) 
                { 
                //设置拖拉模式,ACTION_DOWN是单指进入屏幕的事件 
                case MotionEvent.ACTION_DOWN: 
                savedMatrix.set(matrix); 
                start.set(event.getX(), event.getY()); 
                //Log.d(TAG, "mode=DRAG" ); 
                if(previousMode == ZOOM)
                    mode = DRAG; 
                break; 
             //单指离开屏幕,此处可能是拖动位置,也可能是滑动进入下一页
             case MotionEvent.ACTION_UP: 
                 if(previousMode == NONE || (!checkImageLocation()))//如果不是拖拉模式,就判断翻页
                 {
                     mode = NONE;
                     previousMode = NONE;
                     if(event.getX() - start.x > 200)
                        {
                            if(index > 0)
                            {
                                index--;
                                //添加loading界面
                                setProgressBarIndeterminateVisibility(true);
                                new Thread(imageResourceRunnable).start();

                                view.setText(String.valueOf(index+1)+"/"+String.valueOf(imageUrlList.size()));
                            }
                        } 
                        //向左滑动
                        else if(event.getX() - start.x < -200)
                        {
                            if(index < imageUrlList.size()-1)
                            {
                                index++;
                                //添加loading界面
                                setProgressBarIndeterminateVisibility(true);
                                new Thread(imageResourceRunnable).start();

                                view.setText(String.valueOf(index+1)+"/"+String.valueOf(imageUrlList.size()));
                            }
                        }
                 }
            //多指,离开屏幕事件
             case MotionEvent.ACTION_POINTER_UP: 
                //mode = NONE; 
                //Log.d(TAG, "mode=NONE" ); 
                break; 
             //设置多点触摸模式 ,ACTION_POINTER_DOWN 多手指进入屏幕
             case MotionEvent.ACTION_POINTER_DOWN: 
                 oldDist = spacing(event); 
                 previousMode = ZOOM;
                 //Log.d(TAG, "oldDist=" + oldDist); 
                 if (oldDist > 10f) { 
                    savedMatrix.set(matrix); 
                    midPoint(mid, event); 
                    mode = ZOOM; 
                   // Log.d(TAG, "mode=ZOOM" ); 
                 } 
                 break; 
               //若为DRAG模式,则点击移动图片 
            //ACTION_MOVE 拖动屏幕事件
             case MotionEvent.ACTION_MOVE: 
                 if (mode == DRAG && previousMode == ZOOM) 
                 { 
                     if(!checkImageLocation())
                         break;
                    matrix.set(savedMatrix); 
                    // 设置位移 
                    matrix.postTranslate(event.getX() - start.x, 
                   event.getY() - start.y); 
                 } 
                 //若为ZOOM模式,则多点触摸缩放 
                    else if (mode == ZOOM) 
                    { 
                        //获取Matrix 矩阵到数组中
                        float[] matrixValues = new float[9];
                        matrix.getValues(matrixValues);

                        if(spacing(event)!=-1)
                        {
                            float newDist = spacing(event); 
                            //Log.d(TAG, "newDist=" + newDist); 
                            if (newDist > 10f) 
                            { 
                                matrix.set(savedMatrix); 
                                float scale = newDist / oldDist;
                                //设置缩放比例和图片中点位置 
                                if(!(scale < 1 && matrixValues[0]<=0.4))
                                    matrix.postScale(scale, scale, mid.x, mid.y); 
                                else 
                                    matrix.postScale(1, 1, mid.x, mid.y);
                                previousMode = ZOOM;
                            } 
                        }
                 } 
                 break; 
           } 
            //更新ImageView
            imageView.setImageMatrix(matrix);
            return true;
        }
        private float spacing(MotionEvent event) 
        {
            try
            {
                float x = event.getX(0) - event.getX(1); 
                float y = event.getY(0) - event.getY(1); 
                return FloatMath.sqrt(x * x + y * y); 
            } catch (Exception e)
            {
                e.printStackTrace();
            }
            return -1;
        } 
        //计算中点位置 
        private void midPoint(PointF point, MotionEvent event) 
        { 
              float x = event.getX(0) + event.getX(1); 
              float y = event.getY(0) + event.getY(1); 
              point.set(x / 2, y / 2); 
        }
        /**
         * 计算当前图片与屏幕的位置关系
         * @return 如果返回为真就拖动
         * 如果返回为假,就切换图片
         */
        @SuppressWarnings("deprecation")
        private boolean checkImageLocation()
        {
            float[] locatons = new float[9];
            matrix.getValues(locatons);
            Rect rect = imageView.getDrawable().getBounds();
            float left = locatons[2];
            float top = locatons[5];
            float right = left+rect.width()*locatons[0];
            float bottom = top+rect.height()*locatons[0];
            int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
            int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
            if((screenWidth-left< 200) || (right<200) || (screenHeight-top<500) || bottom<500)
                return false;
            return true;
        }

    });

}

/**
 * 启动线程加载图片链接地址
 */
Runnable imagesRunnable = new Runnable()
{
    public void run()
    {
        ImageSpider  imageSpider = new ImageSpider(url);
        imageUrlList = imageSpider.spider();
    }
};

/**
 * 启动线程加载图片
 */
Runnable imageResourceRunnable = new Runnable()
{
    public void run()
    {
        //等待另一个线程加载完毕
        while(imageUrlList == null)
        {
            try
            {
                Thread.sleep(500);
            } catch (InterruptedException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        URL imageUrl = null;    
        try
        {
            imageUrl = new URL(imageUrlList.get(index));
            HttpURLConnection connection = (HttpURLConnection)imageUrl.openConnection();
            //设置Referer信息
            connection.addRequestProperty("Referer", "www.yeetrack.com");
            //10秒超时
            connection.setConnectTimeout(10000);
            connection.setDoInput(true);
            connection.setUseCaches(true);
            InputStream is = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
            connection.disconnect();
        } catch (MalformedURLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //加载完毕,通知主线程
        Bundle bundle = new Bundle();
        bundle.putString("status", "ok");
        Message msg = new Message();
        msg.setData(bundle);
        handler.sendMessage(msg);

    }
};
}

转载请保留链接地址: https://www.yeetrack.com/?p=600