//将Bitmap处理为圆形的图片
private Bitmap circlePic(Bitmap bitmap){
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int r = width < height ? width/2:height/2; //圆的半径,取宽和高中较小的,以便于显示没有空白
Bitmap outBitmap = Bitmap.createBitmap(r*2, r*2, Bitmap.Config.ARGB_8888); //创建一个刚好2r大小的Bitmap
Canvas canvas = new Canvas(outBitmap); // 这里的这个Canvas就是我们用来绘制照片的Canvas
final int color =0xff424242;
final Paint paint = new Paint();
/**
* 截取图像的中心的一个正方形,用于在原图中截取
* 坐标如下:
* 1.如果 w < h , 左上坐标(0, (h-w)/2) , 右上坐标(w, (h+w)/2)
* 2.如果 w > h , 左上坐标((w-h)/2, 0) , 右上坐标((w+h)/2, h)
*/
final Rect rect = new Rect( width < height ? 0 : (width-height)/2, width < height ? (height-width)/2 : 0,
width < height ? width : (width+height)/2, (width < height ? (height+width)/2 : height));
//创建一个直径大小的正方形,用于设置canvas的显示与设置画布截取
final Rect rect2 = new Rect( 0, 0, r*2, r*2);
//提高精度,用于消除锯齿
final RectF rectF = new RectF(rect2);
//下面是设置画笔和canvas
paint.setAntiAlias(true);
canvas.drawARGB(0,0,0,0);
paint.setColor(color);
//设置圆角,半径都为r,大小为rect2,这样绘制出来的就是一个圆形了
canvas.drawRoundRect(rectF, r, r, paint);
//设置图像重叠时的显示方式,这个设置很重要,设置了这个属性之后我们画照片进去就会以交集的形式截取,这样就会绘制出圆形的图片了
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
//绘制图像到canvas
canvas.drawBitmap(bitmap, rect, rect2, paint);
return outBitmap;
}这样圆形的图片就处理好了。
ImageView myPhoto = (ImageView) this.findViewById(R.id.myPhoto);
//my_photo.setImageResource(R.drawable.ic_launcher);
//得到Resources对象
Resources r = getResources();
WindowManager manage=getWindowManager();
Display display=manage.getDefaultDisplay();
int screenWidth=display.getWidth();
//以数据流的方式读取资源
InputStream is = null;
if(screenWidth > 480) {//这段代码是我适应不同的屏幕大小来显示了不同的照片,其实也有不同的处理方式,不过我觉得这样也能满足我的需求
is = r.openRawResource(R.drawable.my_photo);
} else {
is = r.openRawResource(R.drawable.my_photo1);
}
//获取到BitmapDrawable对象
BitmapDrawable bmpDraw = new BitmapDrawable(is);
//获得Bitmap
Bitmap bmp = bmpDraw.getBitmap();
myPhoto.setImageBitmap(circlePic(bmp));//绘制好的圆形照片设置到ImageView中
myPhoto.setOnClickListener(new PhotoClickListener());//设置一个点击事件,后面再说好了,我们已经绘制了圆形的图片和整体的布局了。也就是,我们做到了这一个画面:原文:http://blog.csdn.net/xjyzxx/article/details/21524741