Android自定义裁剪图片

	//1.构建Bitmap   
	    WindowManager windowManager = getWindowManager();   
	    Display display = windowManager.getDefaultDisplay();   
	    int w = display.getWidth();   
	    int h = display.getHeight();   
	       
	    Bitmap Bmp = Bitmap.createBitmap( w, h, Config.ARGB_8888 );       
	       
	    //2.获取屏幕   
	    View decorview = this.getWindow().getDecorView();    
	    decorview.setDrawingCacheEnabled(true);    
	    Bmp = decorview.getDrawingCache();    
	    iv_image.setImageBitmap(Bmp);
//	    String SavePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/AndyDemo/ScreenImage"; 
//	    
//	    //3.保存Bitmap    
//	    try {   
//	        File path = new File(SavePath);   
//	        //文件   
//	        String filepath = SavePath + "/Screen_1.png";   
//	        File file = new File(filepath);   
//	        if(!path.exists()){   
//	            path.mkdirs();   
//	        }   
//	        if (!file.exists()) {   
//	            file.createNewFile();   
//	        }   
//	           
//	        FileOutputStream fos = null;   
//	        fos = new FileOutputStream(file);   
//	        if (null != fos) {   
//	            Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);   
//	            fos.flush();   
//	            fos.close();     
//	               
//	            Toast.makeText(this, "截屏文件已保存至SDCard/AndyDemo/ScreenImage/下", Toast.LENGTH_LONG).show();   
//	        }   
//	   
//	    } catch (Exception e) {   
//	        e.printStackTrace();   
//	    }   
	    
	    
	  /*  View view = getWindow().getDecorView();   
        view.setDrawingCacheEnabled(true);   
        view.buildDrawingCache();   
        Bitmap b1 = view.getDrawingCache();   
        // 获取状态栏高度   
        Rect frame = new Rect();   
        getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);   
        int statusBarHeight = frame.top;   
        System.out.println(statusBarHeight);   
        // 获取屏幕长和高   
        int width = getWindowManager().getDefaultDisplay().getWidth();   
        int height = getWindowManager().getDefaultDisplay()   
                .getHeight();   
        // 去掉标题栏 //Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);   
//        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height   
//                - statusBarHeight);   
//        view.destroyDrawingCache();   
        
        FileOutputStream fos = null;   
        try {   
            fos = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsoluteFile()+"/screen.png");   
            if (null != fos) {   
                b1.compress(Bitmap.CompressFormat.PNG, 90, fos);   
                fos.flush();   
                fos.close();   
            }   
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   */


http://www.dewen.org/q/3158


android获取控件位置坐标,屏幕尺寸,标题栏,状态栏高度

 1.屏幕尺寸,源代码如下:

DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int screenWidth=metrics.widthPixels;            //屏幕宽度
    int .screenHeight=metrics.heightPixels;        //屏幕高度

     这段代码可以插入到Activity的onCreate()函数中。


    2.获取标题栏、状态栏高度:

Rect rect = new Rect(); 
    Window win = this.getWindow(); 
    win.getDecorView().getWindowVisibleDisplayFrame(rect); 
    int statusBarHeight = rect.top; 
    int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop(); 
    int titleBarHeight = contentViewTop - Variable.statusBarHeight;    

//statusBarHeight为状态栏高度,titleBarHeight为标题栏高度

getLocationOnScreen 计算该视图在全局坐标系中的x,y值,(注意这个值是要从屏幕顶端算起,也就是包括了通知栏的高度)//获取在当前屏幕内的绝对坐标 
getLocationInWindow 计算该视图在它所在的widnow的坐标x,y值,//获取在整个窗口内的绝对坐标

getLeft , getTopgetBottomgetRight, 这一组是获取相对在它父亲里的坐标
int[] location = new  int[2] ;
view.getLocationInWindow(location); //获取在当前窗口内的绝对坐标
view.getLocationOnScreen(location);//获取在整个屏幕内的绝对坐标
location [0]--->x坐标,location [1]--->y坐标


实际成型代码

package com.example.trimimage;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Bitmap.Config;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.FloatMath;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

public class MainActivity extends Activity implements OnTouchListener {

	private ImageView image;
	private View view1;
	private View view2;
	private View view3;
	private View view0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void trimScreen() {
		// 1.构建Bitmap
		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		int w = display.getWidth();
		int h = display.getHeight();

		Bitmap Bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);

		// 2.获取屏幕
		View decorview = this.getWindow().getDecorView();
		decorview.setDrawingCacheEnabled(true);
		Bmp = decorview.getDrawingCache();
		int[] location = new int[2];
		view2.getLocationOnScreen(location);// 获取在整个屏幕内的绝对坐标
		Bitmap bm = Bitmap.createBitmap(Bmp, location[0], location[1],
				view2.getWidth(), view2.getHeight());
		image.setImageBitmap(bm);

		/**
		 * statusBarHeight:38,contentViewTop:110,location1:x:0,y:263,location2:x
		 * :0,y:263 top:78,bottom:696left:0,right:540
		 */

		Rect rect = new Rect();
		Window win = this.getWindow();
		win.getDecorView().getWindowVisibleDisplayFrame(rect);
		int statusBarHeight = rect.top;
		int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT)
				.getTop();
		// int titleBarHeight = contentViewTop - Variable.statusBarHeight;

		int[] location1 = new int[2];
		int[] location2 = new int[2];
		view2.getLocationInWindow(location1); // 获取在当前窗口内的绝对坐标
		view2.getLocationOnScreen(location2);// 获取在整个屏幕内的绝对坐标

		int top = view2.getTop();
		int bottom = view2.getBottom();
		int left = view2.getLeft();
		int right = view2.getRight();

		System.out.println("statusBarHeight:" + statusBarHeight
				+ ",contentViewTop:" + contentViewTop + ",location1:x:"
				+ location1[0] + ",y:" + location1[1] + ",location2:x:"
				+ location2[0] + ",y:" + location2[1]);
		System.out.println("top:" + top + ",bottom:" + bottom + "left:" + left
				+ ",right:" + right);

	}

	private void initView() {
		view0 = findViewById(R.id.view0);
		view0.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				image.setScaleType(ScaleType.CENTER_CROP);
				trimScreen();
			}
		});
		image = (ImageView) findViewById(R.id.image);
		view1 = findViewById(R.id.view1);
		view2 = findViewById(R.id.view2);
		view3 = findViewById(R.id.view3);
		frame = (FrameLayout) findViewById(R.id.frame);
		frame.setOnTouchListener(this);
		LinearLayout.LayoutParams params2 = (android.widget.LinearLayout.LayoutParams) view2
				.getLayoutParams();
		params2.height = getWindowManager().getDefaultDisplay().getWidth();
		params2.width = getWindowManager().getDefaultDisplay().getWidth();
		view2.setLayoutParams(params2);
		LinearLayout.LayoutParams params1 = (android.widget.LinearLayout.LayoutParams) view1
				.getLayoutParams();
		params1.weight = 1;
		LinearLayout.LayoutParams params3 = (android.widget.LinearLayout.LayoutParams) view3
				.getLayoutParams();
		params1.weight = 1;
	}

	private Matrix matrix = new Matrix();
	private Matrix savedMatrix = new Matrix();
	static final int NONE = 0;
	static final int DRAG = 1;
	static final int ZOOM = 2;
	int mode = NONE;
	// Remember some things for zooming
	PointF start = new PointF();
	PointF mid = new PointF();
	float oldDist = 1f;
	private FrameLayout frame;

	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(x * x + y * y);
	}

	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);
	}
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		Log.d("Infor", "size:" + event.getSize());
		if (event.getActionMasked() == MotionEvent.ACTION_POINTER_UP)
			Log.d("Infor", "多点操作");
		switch (event.getActionMasked()) {
		case MotionEvent.ACTION_DOWN:
			image.setScaleType(ScaleType.MATRIX);
			matrix.set(image.getImageMatrix());
			savedMatrix.set(matrix);
			start.set(event.getX(), event.getY());
			Log.d("Infor", "触摸了...");
			mode = DRAG;
			break;
		case MotionEvent.ACTION_POINTER_DOWN: // 多点触控
			oldDist = this.spacing(event);
			if (oldDist > 10f) {
				Log.d("Infor", "oldDist" + oldDist);
				savedMatrix.set(matrix);
				midPoint(mid, event);
				mode = ZOOM;
			}
			break;
		case MotionEvent.ACTION_POINTER_UP:
			mode = NONE;
			break;
		case MotionEvent.ACTION_MOVE:
			if (mode == DRAG) { // 此实现图片的拖动功能...
				matrix.set(savedMatrix);
				matrix.postTranslate(event.getX() - start.x, event.getY()
						- start.y);
			} else if (mode == ZOOM) {// 此实现图片的缩放功能...
				float newDist = spacing(event);
				if (newDist > 10) {
					matrix.set(savedMatrix);
					float scale = newDist / oldDist;
					matrix.postScale(scale, scale, mid.x, mid.y);
				}
			}
			break;
		}
		image.setImageMatrix(matrix);
		return true;

	}
	/*@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		
		 * 087 Log.d("Infor", "类别:"+event.getAction()); 088 Log.d("Infor",
		 * "mask:"+event.getActionMasked()); 089 Log.d("Infor",
		 * "index:"+event.getActionIndex()); 090 Log.d("Infor",
		 * "points:"+event.getPointerCount());
		 
		Log.d("Infor", "size:" + event.getSize());
		if (event.getActionMasked() == MotionEvent.ACTION_POINTER_UP)
			Log.d("Infor", "多点操作");
		switch (event.getActionMasked()) {
		case MotionEvent.ACTION_DOWN:
			image.setScaleType(ScaleType.MATRIX);
			matrix.set(image.getImageMatrix());
			savedMatrix.set(matrix);
			start.set(event.getX(), event.getY());
			Log.d("Infor", "触摸了...");
			mode = DRAG;
			break;
		case MotionEvent.ACTION_POINTER_DOWN: // 多点触控
			oldDist = this.spacing(event);
			if (oldDist > 10f) {
				Log.d("Infor", "oldDist" + oldDist);
				savedMatrix.set(matrix);
				midPoint(mid, event);
				mode = ZOOM;
			}
			break;
		case MotionEvent.ACTION_POINTER_UP:
			mode = NONE;
			break;
		case MotionEvent.ACTION_MOVE:
			if (mode == DRAG) { // 此实现图片的拖动功能...
				matrix.set(savedMatrix);
				matrix.postTranslate(event.getX() - start.x, event.getY()
						- start.y);
			} else if (mode == ZOOM) {// 此实现图片的缩放功能...
				float newDist = spacing(event);
				if (newDist > 10) {
					matrix.set(savedMatrix);
					float scale = newDist / oldDist;
					matrix.postScale(scale, scale, mid.x, mid.y);
				}
			}
			break;
		}
		image.setImageMatrix(matrix);
		return false;

	}
	*/
	
	
	
	
	
	/*
	 * private float x; // 图片移动前的x轴坐标 private float y; // 图片移动前的y轴坐标 private
	 * Matrix newMatrix = new Matrix(); // 用来移动图片的矩阵 private Matrix oldMatrix =
	 * new Matrix(); // 图片移动前的矩阵 private int type; // 操作类型, 一根手指触摸还是两根手指触摸
	 * private float start; // 第二根手指按下时的距离 private float end; // 两根手指移动后的距离
	 * private PointF point; // 放大时的中心点
	 * 
	 * @Override public boolean onTouchEvent(MotionEvent event) { switch
	 * (event.getAction() & MotionEvent.ACTION_MASK) { case
	 * MotionEvent.ACTION_DOWN: type = 1; x = event.getX(); y = event.getY();
	 * oldMatrix.set(image.getImageMatrix()); break; case
	 * MotionEvent.ACTION_MOVE: newMatrix.set(oldMatrix); if (type == 1) { //
	 * 1根手指触摸 // newMatrix.postTranslate(event.getX() - x, event.getY() - y);
	 * newMatrix.set(oldMatrix); // 设置成按下时记住的位置
	 * newMatrix.postTranslate(event.getX() - x, event.getY() - y); // 改变位置
	 * 
	 * } else { // 2跟手指触摸 image.setScaleType(ScaleType.MATRIX); end =
	 * countDistance(event); // 计算结束时距离 float scale = end / start; // 计算缩放比例
	 * newMatrix.postScale(scale, scale, point.x, point.y); // 设置缩放 } break;
	 * case MotionEvent.ACTION_POINTER_DOWN: type = 2; start =
	 * countDistance(event); // 计算开始时距离 point = countPoint(event); // 计算中心点
	 * oldMatrix.set(image.getImageMatrix()); break; }
	 * image.setImageMatrix(newMatrix); // 改变图片 return true; }
	 * 
	 * public float countDistance(MotionEvent event) { float a = event.getX(1) -
	 * event.getX(0); // x轴距离 float b = event.getY(1) - event.getY(0); // y轴距离
	 * return (float) Math.sqrt(a * a + b * b); // 勾股定理 }
	 * 
	 * public PointF countPoint(MotionEvent event) { float x = (event.getX(0) +
	 * event.getX(1)) / 2; // x轴中间点 float y = (event.getY(0) + event.getY(1)) /
	 * 2; // y轴中间点 return new PointF(x, y); }
	 */

}



    

    

        

        
            
            
            
        
    




你可能感兴趣的:(Android常用技巧)