本文转自:

http://blog.csdn.net/hopezhangbo/article/details/7356571

 

 
  
  1. View view = activity.getWindow().getDecorView();    
  2. view.setDrawingCacheEnabled(true);    
  3. view.buildDrawingCache();    
  4. bitmap = view.getDrawingCache();   

然后我们需呀计算出我们选定区域的坐标点,注意正选和反选的计算方式不同 ,

 

 
  
  1. public boolean onTouch(View v, MotionEvent event) {    
  2.      if(event.getAction() == MotionEvent.ACTION_DOWN){    
  3.             x = 0;    
  4.             y = 0;    
  5.             width = 0;    
  6.             height = 0;    
  7.             x = (int) event.getX();    
  8.             y = (int) event.getY();    
  9.         }    
  10.       if(event.getAction() == MotionEvent.ACTION_MOVE){    
  11.             m = (int) event.getX();    
  12.             n = (int) event.getY();    
  13.             myView.setSeat(x, y, m, n);    
  14.             myView.postInvalidate();    
  15.         }    
  16.       if(event.getAction() == MotionEvent.ACTION_UP){    
  17.     if(event.getX()>x){    
  18.          width = (int)event.getX()-x;    
  19.     }else{    
  20.          width = (int)(x-event.getX());    
  21.           x = (int) event.getX();    
  22.     }    
  23.                  if(event.getY()>y){    
  24.          height = (int) event.getY()-y;    
  25.      }else{    
  26.          height = (int)(y-event.getY());    
  27.           y = (int) event.getY();    
  28.     }    
  29.     p_w_picpath2.setImageBitmap(getBitmap(this));    
  30.         }    
  31.     if(myView.isSign()){    
  32.          return false;    
  33.     }else{    
  34.           return true;    
  35.     }    
  36. }  

然后为我们计算出来的坐标区域添加选中效果

 
  
  1. protected void onDraw(Canvas canvas) {    
  2.          if(sign){    
  3.     paint.setColor(Color.TRANSPARENT);    
  4.          }else{    
  5.     paint.setColor(Color.RED);    
  6.     paint.setAlpha(80);    
  7.     canvas.drawRect(new Rect(x, y, m, n), paint);    
  8.            }    
  9.     super.onDraw(canvas);    
  10. }   

最后生成我们需要的图片展示出来,顺便保存到SD卡下一张。

 
  
  1. Rect frame = new Rect();    
  2.       activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);    
  3.       int toHeight = frame.top;    
  4.       bitmap = Bitmap.createBitmap(bitmap, x, y+2*toHeight, width, height);    
  5.       try {    
  6.     FileOutputStream fout = new FileOutputStream("mnt/sdcard/test.png");    
  7.     bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);    
  8.         } catch (FileNotFoundException e) {    
  9.             // TODO Auto-generated catch block    
  10.             e.printStackTrace();    
  11.         }    
  12.         view.setDrawingCacheEnabled(false);