其實實現方式很簡單,首先我們需要做的就是截取整個屏幕生成一個bitmap對象
Android實現指定區域截屏的實現源碼下載:
免費下載地址在 http://linux.linuxidc.com/
用戶名與密碼都是www.linuxidc.com
具體下載目錄在 /2012年資料/3月/9日/Android實現指定區域截屏的實現【附源碼】/
- View view = activity.getWindow().getDecorView();
- view.setDrawingCacheEnabled(true);
- view.buildDrawingCache();
- bitmap = view.getDrawingCache();
然後我們需呀計算出我們選定區域的坐標點,注意正選和反選的計算方式不同 ,
- public boolean onTouch(View v, MotionEvent event) {
- if(event.getAction() == MotionEvent.ACTION_DOWN){
- x = 0;
- y = 0;
- width = 0;
- height = 0;
- x = (int) event.getX();
- y = (int) event.getY();
- }
- if(event.getAction() == MotionEvent.ACTION_MOVE){
- m = (int) event.getX();
- n = (int) event.getY();
- myView.setSeat(x, y, m, n);
- myView.postInvalidate();
- }
- if(event.getAction() == MotionEvent.ACTION_UP){
- if(event.getX()>x){
- width = (int)event.getX()-x;
- }else{
- width = (int)(x-event.getX());
- x = (int) event.getX();
- }
- if(event.getY()>y){
- height = (int) event.getY()-y;
- }else{
- height = (int)(y-event.getY());
- y = (int) event.getY();
- }
- image2.setImageBitmap(getBitmap(this));
- }
- if(myView.isSign()){
- return false;
- }else{
- return true;
- }
- }
然後為我們計算出來的坐標區域添加選中效果
- protected void onDraw(Canvas canvas) {
- if(sign){
- paint.setColor(Color.TRANSPARENT);
- }else{
- paint.setColor(Color.RED);
- paint.setAlpha(80);
- canvas.drawRect(new Rect(x, y, m, n), paint);
- }
- super.onDraw(canvas);
- }
最後生成我們需要的圖片展示出來,順便保存到SD卡下一張。
- Rect frame = new Rect();
- activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
- int toHeight = frame.top;
- bitmap = Bitmap.createBitmap(bitmap, x, y+2*toHeight, width, height);
- try {
- FileOutputStream fout = new FileOutputStream("mnt/sdcard/test.png");
- bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- view.setDrawingCacheEnabled(false);