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

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

  

 

首先讲解一些代码

<ImageView android:id="@+id/screenshot_img"android:layout_width="match_parent"android:layout_height="match_parent"android:scaleType="matrix"/>

图片属性要设置成android:scaleType="matrix",这样图片才可以通过触摸,放大缩小.

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

public class MainActivity extends Activity {private Button btnImg;/*** 表示选择的是相机--0*/private final int IMAGE_CAPTURE = 0;/*** 表示选择的是相册--1*/private final int IMAGE_MEDIA = 1;/*** 图片保存SD卡位置*/private final static String IMG_PATH = Environment.getExternalStorageDirectory() + "/chillax/imgs/";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnImg = (Button)findViewById(R.id.btn_find_img);btnImg.setOnClickListener(BtnClick);}OnClickListener BtnClick = new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubsetImage();}};/*** 选择图片*/public void setImage() {final AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle("选择图片");builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});builder.setPositiveButton("相机", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");startActivityForResult(intent, IMAGE_CAPTURE);}});builder.setNeutralButton("相册", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Intent intent = new Intent(Intent.ACTION_GET_CONTENT);intent.setType("image/*");startActivityForResult(intent, IMAGE_MEDIA);}});AlertDialog alert = builder.create();alert.show();}/*** 根据用户选择,返回图片资源*/public void onActivityResult(int requestCode, int resultCode, Intent data) {ContentResolver resolver = this.getContentResolver();BitmapFactory.Options options = new BitmapFactory.Options();options.inSampleSize = 2;// 图片高宽度都为本来的二分之一,即图片大小为本来的大小的四分之一options.inTempStorage = new byte[5 * 1024];if (data != null){if (requestCode == IMAGE_MEDIA){try {if(data.getData() == null){}else{// 获得图片的uriUri uri = data.getData();// 将字节数组转换为ImageView可调用的Bitmap对象Bitmap bitmap = BitmapFactory.decodeStream(resolver.openInputStream(uri), null,options);//图片路径String imgPath = IMG_PATH+"Test.png";//保存图片saveFile(bitmap, imgPath);Intent i = new Intent(MainActivity.this,ScreenshotImg.class);i.putExtra("ImgPath", imgPath);this.startActivity(i);}} catch (Exception e) {System.out.println(e.getMessage());}}else if(requestCode == IMAGE_CAPTURE) {// 相机if (data != null) {if(data.getExtras() == null){}else{// 相机返回的图片数据Bitmap bitmap = (Bitmap) data.getExtras().get("data");//图片路径String imgPath = IMG_PATH+"Test.png";//保存图片saveFile(bitmap, imgPath);Intent i = new Intent(MainActivity.this,ScreenshotImg.class);i.putExtra("ImgPath", imgPath);this.startActivity(i);}}}}}/*** 保存图片到app指定路径* @param bm头像图片资源* @param fileName保存名称*/public static void saveFile(Bitmap bm, String filePath) {try {String Path = filePath.substring(0, filePath.lastIndexOf("/"));File dirFile = new File(Path);if (!dirFile.exists()) {dirFile.mkdirs();}File myCaptureFile = new File(filePath);BufferedOutputStream bo = null;bo = new BufferedOutputStream(new FileOutputStream(myCaptureFile));bm.compress(Bitmap.CompressFormat.PNG, 100, bo);bo.flush();bo.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

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

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);

图片缩放,截图类:

public class ScreenshotImg extends Activity {private LinearLayout imgSave;private ImageView imgView,imgScreenshot;private String imgPath;private static final int NONE = 0;private static final int DRAG = 1;private static final int ZOOM = 2;private int mode = NONE;private float oldDist;private Matrix matrix = new Matrix();private Matrix savedMatrix = new Matrix();private PointF start = new PointF();private PointF mid = new PointF();@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.img_screenshot);imgView = (ImageView)findViewById(R.id.screenshot_img);imgScreenshot = (ImageView)findViewById(R.id.screenshot);imgSave = (LinearLayout)findViewById(R.id.img_save);Intent i = getIntent();imgPath = i.getStringExtra("ImgPath");Bitmap bitmap = getImgSource(imgPath);if(bitmap!=null){imgView.setImageBitmap(bitmap);imgView.setOnTouchListener(touch);imgSave.setOnClickListener(imgClick);}}OnClickListener imgClick = new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubimgView.setDrawingCacheEnabled(true);Bitmap bitmap = Bitmap.createBitmap(imgView.getDrawingCache());int w = imgScreenshot.getWidth();  int h = imgScreenshot.getHeight();  int left = imgScreenshot.getLeft();   int right = imgScreenshot.getRight();   int top = imgScreenshot.getTop();   int bottom = imgScreenshot.getBottom();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);MainActivity.saveFile(targetBitmap, imgPath);Toast.makeText(getBaseContext(), "保存成功", Toast.LENGTH_LONG).show();finish();}};/*** 触摸事件*/OnTouchListener touch = new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {ImageView view = (ImageView) v;switch (event.getAction() & MotionEvent.ACTION_MASK) {case MotionEvent.ACTION_DOWN:savedMatrix.set(matrix); // 把原始 Matrix对象保存起来start.set(event.getX(), event.getY()); // 设置x,y坐标mode = DRAG;break;case MotionEvent.ACTION_UP:case MotionEvent.ACTION_POINTER_UP:mode = NONE;break;case MotionEvent.ACTION_POINTER_DOWN:oldDist = spacing(event);if (oldDist > 10f) {savedMatrix.set(matrix);midPoint(mid, event); // 求出手指两点的中点mode = ZOOM;}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 > 10f) {matrix.set(savedMatrix);float scale = newDist / oldDist;matrix.postScale(scale, scale, mid.x, mid.y);}}break;}System.out.println(event.getAction());view.setImageMatrix(matrix);return true;}};//求两点距离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);}/*** 從指定路徑讀取圖片資源*/public Bitmap getImgSource(String pathString) {Bitmap bitmap = null;BitmapFactory.Options opts = new BitmapFactory.Options();
//      opts.inSampleSize = 2;try {File file = new File(pathString);if (file.exists()) {bitmap = BitmapFactory.decodeFile(pathString, opts);}if (bitmap == null) {return null;} else {return bitmap;}} catch (Exception e) {e.printStackTrace();return null;}}}

截图关键语句:

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

转载于:https://www.cnblogs.com/Chillax-KUN/p/3841307.html

《Android开发卷——设置圆形头像,Android截取圆形图片》相关推荐

  1. ComeFuture英伽学院——2020年 全国大学生英语竞赛【C类初赛真题解析】(持续更新)

    视频:ComeFuture英伽学院--2019年 全国大学生英语竞赛[C类初赛真题解析]大小作文--详细解析 课件:[课件]2019年大学生英语竞赛C类初赛.pdf 视频:2020年全国大学生英语竞赛 ...

  2. ComeFuture英伽学院——2019年 全国大学生英语竞赛【C类初赛真题解析】大小作文——详细解析

    视频:ComeFuture英伽学院--2019年 全国大学生英语竞赛[C类初赛真题解析]大小作文--详细解析 课件:[课件]2019年大学生英语竞赛C类初赛.pdf 视频:2020年全国大学生英语竞赛 ...

  3. 信息学奥赛真题解析(玩具谜题)

    玩具谜题(2016年信息学奥赛提高组真题) 题目描述 小南有一套可爱的玩具小人, 它们各有不同的职业.有一天, 这些玩具小人把小南的眼镜藏了起来.小南发现玩具小人们围成了一个圈,它们有的面朝圈内,有的 ...

  4. 信息学奥赛之初赛 第1轮 讲解(01-08课)

    信息学奥赛之初赛讲解 01 计算机概述 系统基本结构 信息学奥赛之初赛讲解 01 计算机概述 系统基本结构_哔哩哔哩_bilibili 信息学奥赛之初赛讲解 02 软件系统 计算机语言 进制转换 信息 ...

  5. 信息学奥赛一本通习题答案(五)

    最近在给小学生做C++的入门培训,用的教程是信息学奥赛一本通,刷题网址 http://ybt.ssoier.cn:8088/index.php 现将部分习题的答案放在博客上,希望能给其他有需要的人带来 ...

  6. 信息学奥赛一本通习题答案(三)

    最近在给小学生做C++的入门培训,用的教程是信息学奥赛一本通,刷题网址 http://ybt.ssoier.cn:8088/index.php 现将部分习题的答案放在博客上,希望能给其他有需要的人带来 ...

  7. 信息学奥赛一本通 提高篇 第六部分 数学基础 相关的真题

    第1章   快速幂 1875:[13NOIP提高组]转圈游戏 信息学奥赛一本通(C++版)在线评测系统 第2 章  素数 第 3 章  约数 第 4 章  同余问题 第 5 章  矩阵乘法 第 6 章 ...

  8. 信息学奥赛一本通题目代码(非题库)

    为了完善自己学c++,很多人都去读相关文献,就比如<信息学奥赛一本通>,可又对题目无从下手,从今天开始,我将把书上的题目一 一的解析下来,可以做参考,如果有错,可以告诉我,将在下次解析里重 ...

  9. 信息学奥赛一本通(C++版) 刷题 记录

    总目录详见:https://blog.csdn.net/mrcrack/article/details/86501716 信息学奥赛一本通(C++版) 刷题 记录 http://ybt.ssoier. ...

  10. 最近公共祖先三种算法详解 + 模板题 建议新手收藏 例题: 信息学奥赛一本通 祖孙询问 距离

    首先什么是最近公共祖先?? 如图:红色节点的祖先为红色的1, 2, 3. 绿色节点的祖先为绿色的1, 2, 3, 4. 他们的最近公共祖先即他们最先相交的地方,如在上图中黄色的点就是他们的最近公共祖先 ...

最新文章

  1. PAT甲级排队问题合集 (持续更新中)
  2. “环太平洋”走进现实,五角大楼研发人与武器互动的意念控制技术
  3. 基于三维数据的深度学习综述
  4. python asyncio文件操作_Python asyncio文档阅读摘要
  5. mysql题目(二学年)
  6. 怎么优化GO语言服务的内存占用
  7. 用BusyBox制作Linux根文件系统
  8. android中屏保功能项目,【Android】一段时间不操作弹出【屏保】效果
  9. WDS服务不能启动-----Service-specific error code 1056767740
  10. Maven传递依赖冲突解决(版本冲突)
  11. java 旅游管理系统
  12. CentOS7 安装 oracle 10g
  13. Linux内核编程打印所有线程信息
  14. chunxunnet
  15. 有效防御DDOS的八规则
  16. 坚持自主可控,长安链ChainMaker全面拥抱国密的技术实践
  17. python爬取天极网手机信息代码
  18. SEO搜狗批量查询收录工具
  19. 将汉字转换成汉语拼音的工具代码
  20. 单片机语音模块JQ8900-16P的几种触发方式与源码配置

热门文章

  1. TypeError: this.$refs.resetFields is not a function解决方法
  2. 谷粒商城-基础篇-环境搭建(P1-P44)
  3. java计算机毕业设计Web商铺租赁管理系统MyBatis+系统+LW文档+源码+调试部署
  4. 十问旷视印奇、唐文斌:AI企业都在经历「死亡之谷」
  5. 最优化方法(学习笔记)-第十一章等式约束优化问题
  6. 区块链中nonce与难度系数
  7. c++ getline()详解
  8. 简单学习识谱(六线谱)
  9. 使用树莓派连接笔记本热点
  10. LaTeX会议论文添加版权信息