直接上代碼吧,若是須要拍照或者從相冊中選擇圖片的功能,推薦一個開源庫,用起來很方便android
http://www.jianshu.com/p/35ce3b82773ecanvas
//裁剪圖片的第三方庫http://www.jianshu.com/p/35ce3b82773e compile 'com.linchaolong.android:imagepicker:1.5'
這個庫能夠設置裁剪時的框是圓形的,可是獲取的圖片仍然是方形的,所以在裁剪後仍然須要對獲取到的照片進行處理,如下爲部分用到的核心方法this
/**
* @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);spa
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect( 0, 0, bitmap.getWidth(), bitmap.getHeight());.net
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;
}orm
上面方面獲取到的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();
}
}