直接上代码吧,如果需要拍照或者从相册中选择图片的功能,推荐一个开源库,用起来很方便
http://www.jianshu.com/p/35ce3b82773e
//裁剪图片的第三方库http://www.jianshu.com/p/35ce3b82773e compile 'com.linchaolong.android:imagepicker:1.5'
这个库可以设置裁剪时的框是圆形的,但是获取的图片仍然是方形的,因此在裁剪后仍然需要对获取到的照片进行处理,以下为部分用到的核心方法
/**
* @param bitmap src图片
* @return
*/
public static Bitmap getCircleBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap( bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas( output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect( 0, 0, bitmap.getWidth(), bitmap.getHeight());
paint.setAntiAlias( true);
paint.setFilterBitmap( true);
paint.setDither( true);
canvas.drawARGB( 0, 0, 0, 0);
paint.setColor( color);
//在画布上绘制一个圆
canvas.drawCircle( bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint);
paint.setXfermode( new PorterDuffXfermode( Mode.SRC_IN));
canvas.drawBitmap( bitmap, rect, rect, paint);
return output;
}
上面方面获取到的bitmap看上去像素并不高,可以尝试使用下面的这种方法
==============================================================
//另一种方式===================== public Bitmap drawCircleView02(Bitmap bitmap){ //前面同上,绘制图像分别需要bitmap,canvas,paint对象 bitmap = Bitmap.createScaledBitmap(bitmap, 128, 128, true);//==========创建的图片的长宽为128 Bitmap bm = Bitmap.createBitmap(128, 128, Bitmap.Config.ARGB_8888);//此处的长宽应该与上一行保持一致 Canvas canvas = new Canvas(bm); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); //这里需要先画出一个圆 canvas.drawCircle(64, 64, 64, paint);//===========此处应该为上面长宽的一半 //圆画好之后将画笔重置一下 paint.reset(); //设置图像合成模式,该模式为只在源图像和目标图像相交的地方绘制源图像 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, 0, 0, paint); return bm; }
//根据URI获取bitmap对象
private Bitmap getBitmapFromUri(Uri uri) {
try {
// 读取uri所在的图片
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//将bitmap保存成文件
public void saveBitmap(String bitName, Bitmap mBitmap) {
File f = new File(bitName);
try {
f.createNewFile();
} catch (IOException e) {
}
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//此处注意,保存格式必须设置为png,文件后缀可以是jpg,但是格式必须是PNG,否则会出现黑色背景
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}