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

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

  

 

首先讲解一些代码

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

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

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

截图关键语句:

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

Android:设置圆形头像,Android截取圆形图片相关推荐

  1. android 设置动态头像,Android实现动态圆环的图片头像控件

    先看效果图: 现在大部分的app上难免会使用到圆形头像,所以今天我给大家分享一个单独使用的,并且周围带有圆环动画的花哨圆形头像控件,本控件是在圆形头像控件基础上实现的,只是在其周围再画一些不同大小的圆 ...

  2. android人脸识显示头像自定义,Android 仿QQ头像自定义截取功能

    看了Android版QQ的自定义头像功能,决定自己实现,随便熟悉下android绘制和图片处理这一块的知识. 先看看效果: 思路分析: 这个效果可以用两个View来完成,上层View是一个遮盖物,绘制 ...

  3. 《Android开发卷——设置圆形头像,Android截取圆形图片》

    在有一些程序开发中,有时候会用到圆形,截取一张图片的一部分圆形,作为头像或者其他. 本实例就是截图圆形,设置头像的.      首先讲解一些代码 <ImageView android:id=&q ...

  4. android 圆形头像,自定义圆形ImageView

    <!--头像--><RelativeLayoutandroid:id="@+id/ll_petInfo"android:layout_width="50 ...

  5. android 自定义圆形头像,android自定义圆形头像

    这几天看了项目框架里面的圆形头像,发现其实这个东西并不是很难的东西,学会了原理,无论圆形头像,五角星头像都可以实现. 目前我上传的Demo里用了两种实现方式,那么我们分别来讲讲这两种实现方式: Bit ...

  6. 圆形头像 android,android 一个简单的实现圆形头像的Demo

    [实例简介] [实例截图] [核心代码] package davidzoomimageviewrounddemo.qq986945193.com.davidzoomimageviewrounddemo ...

  7. android qq 圆形头像,Android仿QQ圆形头像个性名片

    先看看效果图: 中间的圆形头像和光环波形讲解请看:https://www.jb51.net/article/96508.htm 周围的气泡布局,因为布局RatioLayout是继承自ViewGroup ...

  8. Bootstrap—实现圆角、圆形头像和响应式图片

    Bootstrap提供了四种用于<img>类的样式,分别是: .img-rounded:圆角 (IE8 不支持),添加 border-radius:6px 来获得图片圆角: .img-ci ...

  9. Android中替换头像图标和背景图片

    一,修改头像图标和名称 第一步:在res下的drawable--hdpi中导入图片 第二步:在res下的androidManifest.xml中在代码中的application的icon中修改为插入图 ...

  10. android 设置textview 左边,Android设置图片在TextView上、下、左、右

    一种是在布局文件中的设置 android:drawablePadding="5dp"//图片与文案距离 android:drawableBottom="@drawable ...

最新文章

  1. mysql数据库比对视频教程_MySQL数据库全学习实战视频教程(27讲 )
  2. No such file or directory: jupyter-1.0.0.dist-info\\METADATA
  3. 决定把BLOG的文章从CU上同步过来
  4. 牛客题霸 [二叉树的镜像]C++题解/答案
  5. 最让人纠结的等式:0.999...=1
  6. 解决ios上微信无法捕获返回键按钮事件的问题
  7. [leetcode]5341. 最后 K 个数的乘积
  8. [USACO DEC13] 名称记录
  9. 网络安全基础(木马、概述、冰河木马实验)
  10. MySQL 定义条件与处理程序 的详细讲解
  11. CF891D Sloth
  12. 数据库第三次实验报告
  13. TCR-T细胞治疗最新研究进展(2021年2月)
  14. laydate日期时间插件实现不用点击确定
  15. Error: unable to perform an operation on node ‘rabbit@rabbitma‘ please see diamostics infoxmation
  16. Android使用SharedPreferences存储数据
  17. Linux ~ 系统管理。
  18. anaconda安装及配置
  19. 哈佛商学院20部必看电影
  20. omniplan的使用

热门文章

  1. ARM指令B BL BLX BX区别
  2. 【Metashape精品教程5】影像质量评估
  3. lisp全部文本改宋体字型_[推荐]修改任何文字(包括属性块、有名无名块)
  4. 牛车水茶渊品茗,新加坡总理与英国女王同款文化体验
  5. Matlab 菲涅尔系数计算
  6. 6个音效素材库,自媒体必备~
  7. 到底什么是新媒体、什么是互动、什么是互动营销?
  8. 人大金仓 创建表空间_Kingbase人大金仓数据库总结(SQL和JDBC)
  9. python爬取腾讯新闻_python爬虫实战――爬取腾讯新闻 !
  10. “Self-Challenging Improves Cross-Domain Generalization”阅读笔记