前段时间在做一款软件,由于有用户登录,所以必须考虑到截取头像,于是自己尝试去实现类似qq那样获取圆形头像。
首先实现如下界面:
实现代码如下:
Bitmap bitmap = Bitmap.createBitmap(getMeasuredWidth(),getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); canvas.drawCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2, radius, paint); paint.setAlpha(180); paint.setAntiAlias(true); paint.setStyle(Paint.Style.FILL); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT)); Bitmap overBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.over); canvas.drawBitmap(overBitmap,null,sourceRect,paint); return bitmap;即可获取上图所示效果。
接下来就是实现当用户点击截取的时候获取圆形区域图片的时候了。
Bitmap targetBitmap = Bitmap.createBitmap(2 * radius,2 * radius, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setDither(true); Path path = new Path(); path.addCircle(radius, radius, radius, Path.Direction.CCW); canvas.clipPath(path, Region.Op.REPLACE); matrix.postTranslate(-(getWidth() - 2 * radius) / 2, -(getHeight() - 2 * radius) / 2); canvas.drawBitmap(sourceBitmap, matrix, paint);targetBitmap就是要截取的区域。