这是依据翔神那篇高仿微信图像截取改的 能够先去看 Android 高仿微信头像截取 打造不一样的自己定义控件 这篇文章。
眼下还有个小问题。就是截取成圆形图片之后 会有黑色的边框填充。不知道怎么解决。知道怎么解决的大神麻烦告知一声。
改动ClipImageBorderView
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // // 计算矩形区域的宽度 // mWidth = getWidth() - 2 * mHorizontalPadding; // // 计算距离屏幕垂直边界 的边距 // mVerticalPadding = (getHeight() - mWidth) / 2; // mPaint.setColor(Color.parseColor("#aa000000")); // mPaint.setStyle(Style.FILL); // // 绘制左边1 // canvas.drawRect(0, 0, mHorizontalPadding, getHeight(), mPaint); // // 绘制右边2 // canvas.drawRect(getWidth() - mHorizontalPadding, 0, getWidth(), // getHeight(), mPaint); // // 绘制上边3 // canvas.drawRect(mHorizontalPadding, 0, getWidth() - // mHorizontalPadding, mVerticalPadding, mPaint); // // 绘制下边4 // canvas.drawRect(mHorizontalPadding, getHeight() - mVerticalPadding, // getWidth() - mHorizontalPadding, getHeight(), mPaint); // // 绘制外边框 // mPaint.setColor(mBorderColor); // mPaint.setStrokeWidth(mBorderWidth); // mPaint.setStyle(Style.STROKE); // canvas.drawRect(mHorizontalPadding, mVerticalPadding, getWidth() - // mHorizontalPadding, getHeight() - mVerticalPadding, mPaint); if (rf == null || rf.isEmpty()) { r = new Rect(0, 0, getWidth(), getHeight()); rf = new RectF(r); } mPaint.setStyle(Style.STROKE); // 在imageview上面画入背景和 圆形 int sc = canvas.saveLayer(rf, null, Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG | Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG | Canvas.ALL_SAVE_FLAG); mPaint.setColor(Color.parseColor("#aa000000")); mPaint.setStyle(Style.FILL); canvas.drawRect(r, mPaint); mPaint.setXfermode(cur_xfermode); // mPaint.setStyle(Style.STROKE); // 绘制圆形 canvas.drawCircle(getWidth() / 2, getHeight() / 2, mRadius, mPaint); // 绘制边框 canvas.drawCircle(getWidth() / 2, getHeight() / 2, mRadius, mBoderPaint); canvas.restoreToCount(sc); mPaint.setXfermode(null); }
改动 ClipZoomImageView
public Bitmap onClip() { // 获取imageview的bitmap Paint paint = new Paint(); invalidate(); setDrawingCacheEnabled(true); Bitmap bitmap = getDrawingCache().copy(getDrawingCache().getConfig(), false); setDrawingCacheEnabled(false); // 创建你要截取的位图 Bitmap bitmap2 = Bitmap.createBitmap(2 * mRadius, 2 * mRadius, Config.ARGB_8888); Canvas canvas = new Canvas(bitmap2); canvas.drawRoundRect(new RectF(0, 0, 2 * mRadius, 2 * mRadius), mRadius, mRadius, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); RectF dst = new RectF(-bitmap.getWidth() / 2 + mRadius, -getHeight() / 2 + mRadius, bitmap.getWidth() - bitmap.getWidth() / 2 + mRadius, getHeight() - getHeight() / 2 + mRadius); canvas.drawBitmap(bitmap, null, dst, paint); return bitmap2; }