观看此篇文章前,请先阅读上篇文章:高仿QQ头像截取;
本篇之所以为升级版,是在截取头像界面添加了与qq类似的阴影层(裁剪区域以外的部分),且看效果图:
为了适应大家不同需求,这次打了两个包,及上图中一个方形的头像截取demo和一个圆形的;
原理:
方形:
如图:底层即图片层,在上层的画布中,先将裁剪区四周根据裁剪区大小画上阴影,然后在画上裁剪区的白色边框(空心):如下图
主要代码如下:
- @Override
- protected void onDraw(Canvas canvas)
- {
- super.onDraw(canvas);
- // 计算矩形区域的宽度
- mWidth = getWidth() - 2 * mHorizontalPadding;
- // 计算距离屏幕垂直边界 的边距
- mVerticalPadding = (getHeight() - mWidth) / 2;
- // 绘制左边
- canvas.drawRect(0, 0, mHorizontalPadding, getHeight()-mVerticalPadding, mPaintRect);
- // 绘制右边
- canvas.drawRect(getWidth() - mHorizontalPadding, mVerticalPadding, getWidth(),getHeight(), mPaintRect);
- // 绘制上边
- canvas.drawRect(mHorizontalPadding, 0, getWidth(),mVerticalPadding, mPaintRect);
- // 绘制下边
- canvas.drawRect(0, getHeight() - mVerticalPadding,getWidth() - mHorizontalPadding, getHeight(), mPaintRect);
- //绘制边框
- canvas.drawRect( mHorizontalPadding, mVerticalPadding,mHorizontalPadding+mWidth, mVerticalPadding+mWidth, mPaint);
- }
圆形裁剪稍复杂一点,利用到了Xfermode即图像重叠模式中的XOR:抠出重叠区域
实现思路:
画的有点乱,先凑合着看,2,3是用的另一个画布,并将3即实心圆的画笔设置为:
- mPaintCirle.setXfermode(new PorterDuffXfermode(Mode.XOR));
当阴影层和其上部的的实心圆重叠时,则实心圆部分即被抠出,剩下一个中间空洞的阴影层了,然后再将该画布的bitmap画在自定义View的画布上合成,最后画出圆形裁剪区白色边框,主要代码如下:
- protected void onDraw(Canvas canvas)
- {
- super.onDraw(canvas);
- if(mBgBitmap==null){
- mBgBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Config.ARGB_8888);
- mCanvas = new Canvas(mBgBitmap);
- mRect = new RectF(0, 0, getWidth(), getHeight());
- }
- //绘制阴影层
- mCanvas.drawRect(mRect, mPaintRect);
- //绘制实心圆 ,绘制完后,在mCanvas画布中,mPaintRect和mPaintCirle相交部分即被掏空
- mCanvas.drawCircle( getWidth()/2, getHeight()/2, getWidth()/2-mHorizontalPadding, mPaintCirle);
- //将阴影层画进本View的画布中
- canvas.drawBitmap(mBgBitmap, null, mRect, new Paint());
- //绘制圆环
- canvas.drawCircle( getWidth()/2, getHeight()/2, getWidth()/2-mHorizontalPadding, mPaint);
- }
好了,且看源码下载地址,两个demo都包含在内: