在有一些程序开发中,有时候会用到圆形,截取一张图片的一部分圆形,作为头像或者其他.

本实例就是截图圆形,设置头像的.

  

 

首先讲解一些代码

[html]  view plain copy
  1. <ImageView android:id="@+id/screenshot_img"  
  2.        android:layout_width="match_parent"  
  3.        android:layout_height="match_parent"  
  4.        android:scaleType="matrix"/>  
图片属性要设置成android:scaleType="matrix",这样图片才可以通过触摸,放大缩小.


主类功能:点击按钮选择图片或者拍照

[java]  view plain copy
  1. public class MainActivity extends Activity {  
  2.       
  3.     private Button btnImg;  
  4.       
  5.     /** 
  6.      * 表示选择的是相机--0 
  7.      */  
  8.     private final int IMAGE_CAPTURE = 0;  
  9.     /** 
  10.      * 表示选择的是相册--1 
  11.      */  
  12.     private final int IMAGE_MEDIA = 1;  
  13.       
  14.     /** 
  15.      * 图片保存SD卡位置 
  16.      */  
  17.     private final static String IMG_PATH = Environment  
  18.             .getExternalStorageDirectory() + "/chillax/imgs/";  
  19.       
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.activity_main);  
  24.           
  25.         btnImg = (Button)findViewById(R.id.btn_find_img);  
  26.         btnImg.setOnClickListener(BtnClick);  
  27.     }  
  28.       
  29.     OnClickListener BtnClick = new OnClickListener() {  
  30.         @Override  
  31.         public void onClick(View v) {  
  32.             // TODO Auto-generated method stub  
  33.             setImage();  
  34.         }  
  35.     };  
  36.       
  37.     /** 
  38.      * 选择图片 
  39.      */  
  40.     public void setImage() {  
  41.         final AlertDialog.Builder builder = new AlertDialog.Builder(this);  
  42.         builder.setTitle("选择图片");  
  43.         builder.setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  44.             @Override  
  45.             public void onClick(DialogInterface dialog, int which) {}  
  46.         });  
  47.         builder.setPositiveButton("相机"new DialogInterface.OnClickListener() {  
  48.             @Override  
  49.             public void onClick(DialogInterface dialog, int which) {  
  50.                 Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");  
  51.                 startActivityForResult(intent, IMAGE_CAPTURE);  
  52.             }  
  53.         });  
  54.         builder.setNeutralButton("相册"new DialogInterface.OnClickListener() {  
  55.             @Override  
  56.             public void onClick(DialogInterface dialog, int which) {  
  57.                 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);  
  58.                 intent.setType("image/*");  
  59.                 startActivityForResult(intent, IMAGE_MEDIA);  
  60.             }  
  61.         });  
  62.         AlertDialog alert = builder.create();  
  63.         alert.show();  
  64.     }  
  65.       
  66.     /**  
  67.      * 根据用户选择,返回图片资源  
  68.      */  
  69.     public void onActivityResult(int requestCode, int resultCode, Intent data) {  
  70.           
  71.         ContentResolver resolver = this.getContentResolver();  
  72.           
  73.         BitmapFactory.Options options = new BitmapFactory.Options();  
  74.         options.inSampleSize = 2;// 图片高宽度都为本来的二分之一,即图片大小为本来的大小的四分之一  
  75.         options.inTempStorage = new byte[5 * 1024];  
  76.           
  77.         if (data != null){  
  78.             if (requestCode == IMAGE_MEDIA){  
  79.                 try {  
  80.                     if(data.getData() == null){  
  81.                     }else{  
  82.                           
  83.                         // 获得图片的uri  
  84.                         Uri uri = data.getData();  
  85.       
  86.                         // 将字节数组转换为ImageView可调用的Bitmap对象  
  87.                         Bitmap bitmap = BitmapFactory.decodeStream(  
  88.                                 resolver.openInputStream(uri), null,options);  
  89.                           
  90.                         //图片路径  
  91.                         String imgPath = IMG_PATH+"Test.png";  
  92.                           
  93.                         //保存图片  
  94.                         saveFile(bitmap, imgPath);  
  95.                           
  96.                         Intent i = new Intent(MainActivity.this,ScreenshotImg.class);  
  97.                         i.putExtra("ImgPath", imgPath);  
  98.                         this.startActivity(i);  
  99.                           
  100.                     }  
  101.                 } catch (Exception e) {  
  102.                     System.out.println(e.getMessage());  
  103.                 }  
  104.   
  105.             }else if(requestCode == IMAGE_CAPTURE) {// 相机  
  106.                 if (data != null) {  
  107.                     if(data.getExtras() == null){  
  108.                     }else{  
  109.                           
  110.                         // 相机返回的图片数据  
  111.                         Bitmap bitmap = (Bitmap) data.getExtras().get("data");  
  112.                           
  113.                         //图片路径  
  114.                         String imgPath = IMG_PATH+"Test.png";  
  115.                           
  116.                         //保存图片  
  117.                         saveFile(bitmap, imgPath);  
  118.                           
  119.                         Intent i = new Intent(MainActivity.this,ScreenshotImg.class);  
  120.                         i.putExtra("ImgPath", imgPath);  
  121.                         this.startActivity(i);  
  122.                     }  
  123.                 }  
  124.             }  
  125.         }  
  126.     }  
  127.       
  128.     /** 
  129.      * 保存图片到app指定路径 
  130.      * @param bm头像图片资源 
  131.      * @param fileName保存名称 
  132.      */  
  133.     public static void saveFile(Bitmap bm, String filePath) {  
  134.             try {  
  135.                 String Path = filePath.substring(0, filePath.lastIndexOf("/"));  
  136.                 File dirFile = new File(Path);  
  137.                 if (!dirFile.exists()) {  
  138.                     dirFile.mkdirs();  
  139.                 }  
  140.                 File myCaptureFile = new File(filePath);  
  141.                 BufferedOutputStream bo = null;  
  142.                 bo = new BufferedOutputStream(new FileOutputStream(myCaptureFile));  
  143.                 bm.compress(Bitmap.CompressFormat.PNG, 100, bo);  
  144.   
  145.                 bo.flush();  
  146.                 bo.close();  
  147.   
  148.             } catch (FileNotFoundException e) {  
  149.                 e.printStackTrace();  
  150.             } catch (IOException e) {  
  151.                 e.printStackTrace();  
  152.             }  
  153.     }  
  154.       
  155.     @Override  
  156.     public boolean onCreateOptionsMenu(Menu menu) {  
  157.         // Inflate the menu; this adds items to the action bar if it is present.  
  158.         getMenuInflater().inflate(R.menu.main, menu);  
  159.         return true;  
  160.     }  
  161.   
  162. }  

注意:有时候要对图片进行压缩,不然在程序中很容易就造成内存溢出.

BitmapFactory.Options options = new BitmapFactory.Options();


options.inSampleSize = 2;// 图片高宽度都为本来的二分之一


options.inTempStorage = new byte[5 * 1024];


// 获得图片的uri

Uri uri = data.getData();

// 将字节数组转换为ImageView可调用的Bitmap对象
Bitmap bitmap = BitmapFactory.decodeStream(resolver.openInputStream(uri), null,options);


图片缩放,截图类:

[java]  view plain copy
  1. public class ScreenshotImg extends Activity {  
  2.   
  3.     private LinearLayout imgSave;  
  4.     private ImageView imgView,imgScreenshot;  
  5.     private String imgPath;  
  6.       
  7.     private static final int NONE = 0;  
  8.     private static final int DRAG = 1;  
  9.     private static final int ZOOM = 2;  
  10.   
  11.     private int mode = NONE;  
  12.     private float oldDist;  
  13.     private Matrix matrix = new Matrix();  
  14.     private Matrix savedMatrix = new Matrix();  
  15.     private PointF start = new PointF();  
  16.     private PointF mid = new PointF();  
  17.       
  18.     @Override  
  19.     protected void onCreate(Bundle savedInstanceState) {  
  20.         // TODO Auto-generated method stub  
  21.         super.onCreate(savedInstanceState);  
  22.         this.setContentView(R.layout.img_screenshot);  
  23.   
  24.         imgView = (ImageView)findViewById(R.id.screenshot_img);  
  25.         imgScreenshot = (ImageView)findViewById(R.id.screenshot);  
  26.         imgSave = (LinearLayout)findViewById(R.id.img_save);  
  27.           
  28.         Intent i = getIntent();  
  29.         imgPath = i.getStringExtra("ImgPath");  
  30.           
  31.         Bitmap bitmap = getImgSource(imgPath);  
  32.           
  33.         if(bitmap!=null){  
  34.             imgView.setImageBitmap(bitmap);  
  35.             imgView.setOnTouchListener(touch);  
  36.             imgSave.setOnClickListener(imgClick);  
  37.         }  
  38.           
  39.     }  
  40.       
  41.     OnClickListener imgClick = new OnClickListener() {  
  42.         @Override  
  43.         public void onClick(View v) {  
  44.             // TODO Auto-generated method stub  
  45.             imgView.setDrawingCacheEnabled(true);  
  46.             Bitmap bitmap = Bitmap.createBitmap(imgView.getDrawingCache());  
  47.               
  48.             int w = imgScreenshot.getWidth();    
  49.             int h = imgScreenshot.getHeight();    
  50.               
  51.             int left = imgScreenshot.getLeft();     
  52.             int right = imgScreenshot.getRight();     
  53.             int top = imgScreenshot.getTop();     
  54.             int bottom = imgScreenshot.getBottom();  
  55.               
  56.             Bitmap targetBitmap = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);  
  57.                       
  58.             Canvas canvas = new Canvas(targetBitmap);  
  59.             Path path = new Path();  
  60.               
  61.             path.addCircle((float)((right-left) / 2),((float)((bottom-top)) / 2), (float)(w / 2),  
  62.             Path.Direction.CCW);  
  63.               
  64.             canvas.clipPath(path);  
  65.               
  66.             canvas.drawBitmap(bitmap,new Rect(left,top,right,bottom),new Rect(left,top,right,bottom),null);  
  67.               
  68.             MainActivity.saveFile(targetBitmap, imgPath);  
  69.               
  70.             Toast.makeText(getBaseContext(), "保存成功", Toast.LENGTH_LONG).show();  
  71.               
  72.             finish();  
  73.         }  
  74.     };  
  75.       
  76.     /** 
  77.      * 触摸事件 
  78.      */  
  79.     OnTouchListener touch = new OnTouchListener() {  
  80.         @Override  
  81.         public boolean onTouch(View v, MotionEvent event) {  
  82.             ImageView view = (ImageView) v;  
  83.             switch (event.getAction() & MotionEvent.ACTION_MASK) {  
  84.             case MotionEvent.ACTION_DOWN:  
  85.                 savedMatrix.set(matrix); // 把原始 Matrix对象保存起来  
  86.                 start.set(event.getX(), event.getY()); // 设置x,y坐标  
  87.                 mode = DRAG;  
  88.                 break;  
  89.             case MotionEvent.ACTION_UP:  
  90.             case MotionEvent.ACTION_POINTER_UP:  
  91.                 mode = NONE;  
  92.                 break;  
  93.             case MotionEvent.ACTION_POINTER_DOWN:  
  94.                 oldDist = spacing(event);  
  95.                 if (oldDist > 10f) {  
  96.                     savedMatrix.set(matrix);  
  97.                     midPoint(mid, event); // 求出手指两点的中点  
  98.                     mode = ZOOM;  
  99.                 }  
  100.                 break;  
  101.             case MotionEvent.ACTION_MOVE:  
  102.                 if (mode == DRAG) {  
  103.                     matrix.set(savedMatrix);  
  104.                       
  105.                     matrix.postTranslate(event.getX() - start.x, event.getY()  
  106.                             - start.y);  
  107.                 } else if (mode == ZOOM) {  
  108.                     float newDist = spacing(event);  
  109.                     if (newDist > 10f) {  
  110.                         matrix.set(savedMatrix);  
  111.                         float scale = newDist / oldDist;  
  112.                         matrix.postScale(scale, scale, mid.x, mid.y);  
  113.                     }  
  114.                 }  
  115.                 break;  
  116.             }  
  117.             System.out.println(event.getAction());  
  118.             view.setImageMatrix(matrix);  
  119.             return true;  
  120.         }  
  121.     };  
  122.   
  123.     //求两点距离  
  124.     private float spacing(MotionEvent event) {  
  125.     float x = event.getX(0) - event.getX(1);  
  126.     float y = event.getY(0) - event.getY(1);  
  127.     return FloatMath.sqrt(x * x + y * y);  
  128.     }  
  129.   
  130.     //求两点间中点  
  131.     private void midPoint(PointF point, MotionEvent event) {  
  132.     float x = event.getX(0) + event.getX(1);  
  133.     float y = event.getY(0) + event.getY(1);  
  134.     point.set(x / 2, y / 2);  
  135.     }  
  136.       
  137.     /** 
  138.      * 從指定路徑讀取圖片資源 
  139.      */  
  140.     public Bitmap getImgSource(String pathString) {  
  141.           
  142.         Bitmap bitmap = null;  
  143.         BitmapFactory.Options opts = new BitmapFactory.Options();  
  144. //      opts.inSampleSize = 2;  
  145.           
  146.         try {  
  147.             File file = new File(pathString);  
  148.             if (file.exists()) {  
  149.                 bitmap = BitmapFactory.decodeFile(pathString, opts);  
  150.             }  
  151.             if (bitmap == null) {  
  152.                 return null;  
  153.             } else {  
  154.                 return bitmap;  
  155.             }  
  156.         } catch (Exception e) {  
  157.             e.printStackTrace();  
  158.             return null;  
  159.         }  
  160.     }  
  161.       
  162. }  

截图关键语句:

Bitmap targetBitmap = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
               
 Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
       
path.addCircle((float)((right-left) / 2),((float)((bottom-top)) / 2), (float)(w / 2),
Path.Direction.CCW);     //绘制圆形
       
canvas.clipPath(path);
       
canvas.drawBitmap(bitmap,new Rect(left,top,right,bottom),new Rect(left,top,right,bottom),null);    //截图


项目源码:http://download.csdn.net/detail/chillax_li/7120673

(有人说保存图片之后,没打开图片.这是因为我没打开它,要看效果的话,要自己用图库打开,就能看到效果了.这里说明一下)


尊重原创,转载请注明出处:http://blog.csdn.net/chillax_li/article/details/22591681
        

更多相关文章

  1. 浅谈android的selector,背景选择器
  2. Android的selector 背景选择器
  3. Android复制assets目录下的图片到内存
  4. [转]Android(安卓)应用初始化及窗体事件(按键)的分发 [此博文包含
  5. Android(安卓)Studio 设置背景色
  6. 使用Qt5.9开发Android(安卓)应用程序(Windows平台篇)
  7. Android(安卓)Handler 异步消息处理机制的妙用 创建强大的图片加
  8. (4.1.21.4)Android(安卓)Handler 异步消息处理机制的妙用 创建强大
  9. Android(安卓)Studio 无设备打包与有设备打包小记

随机推荐

  1. myisam 表中, 删除数据后运行 OPTIMIZE T
  2. MySQL索引的基础初识
  3. mysql关闭严格模式
  4. MySQL的安装和基本管理
  5. 如何在php imap函数中看到看不见的电子邮
  6. Ubuntu中安装MySql与简单操作
  7. 【mysql 优化 5】左连接和右连接优化
  8. 数据库相关零散知识点记录
  9. mysql 反向生成 er图
  10. 用过mysql存储过程和oracle存储过程的哥