Android 圖片截取人物頭像(仿逗拍),
要求
根據給定的頭部模板,截取資源圖。背景圖可支援拖動,縮放,拖動旋轉
分析
定義剪下浮層,實現背景資源圖的操作view
實現
/** * 初始化繪製筆 */ private void initRectPaint() { mFloatPaint = new Paint(); mFloatPaint.setAlpha(mAlpha); mFloatPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.XOR)); mEdgePaint = new Paint(); mEdgePaint.setColor(Color.parseColor("#ff000000")); mEdgePaint.setAlpha(mAlpha); }@Override public void draw(Canvas canvas) { /** 繪製周圍的背景色 **/ drawEdge(canvas); /** 繪製中間浮層 **/ canvas.drawBitmap(mCropDrawable, mFloatRect.left, mFloatRect.top, mFloatPaint); }
@Override protected void onDraw(Canvas canvas) { canvas.save(); canvas.drawColor(Color.parseColor("#ff1c1c22")); canvas.drawBitmap(mBGHeadBitmap, mFloatRect.left, mFloatRect.top, null); canvas.drawBitmap(mBGBitmap, mBGgmatrix, null); mFloatView.draw(canvas); canvas.restore(); }//手勢操作public boolean onTouchEvent(MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN : eventMode = EventMode.DRAG; x_down = event.getX(); y_down = event.getY(); savedMatrix.set(mBGgmatrix); break; case MotionEvent.ACTION_POINTER_DOWN : eventMode = EventMode.ZOOM; oldDist = spacing(event); mRotation = rotation(event); savedMatrix.set(mBGgmatrix); midPoint(midPoint, event); break; case MotionEvent.ACTION_MOVE : if (eventMode == EventMode.DRAG) { matrix1.set(savedMatrix); matrix1.postTranslate(event.getX() - x_down, event.getY() - y_down); mBGgmatrix.set(matrix1); invalidate(); } else if (eventMode == EventMode.ZOOM) { float rotation = rotation(event) - mRotation; float newDist = spacing(event); float scale = newDist / oldDist; /** 縮放 **/ float values[] = new float[9]; { matrix1.set(savedMatrix); matrix1.postScale(scale, scale, midPoint.x, midPoint.y); } /** 旋轉 **/ matrix1.postRotate(rotation, midPoint.x, midPoint.y); mBGgmatrix.set(matrix1); invalidate(); } break; case MotionEvent.ACTION_UP : case MotionEvent.ACTION_POINTER_UP : eventMode = EventMode.NONE; break; } return true; }
Bitmap tmpBitmap = Bitmap.createBitmap(mScrrenWidth, mScrrenHeight, Config.ARGB_8888); // 背景圖片 Canvas canvas = new Canvas(tmpBitmap); // 建立畫布 canvas.drawBitmap(mBGHeadBitmap, mFloatRect.left, mFloatRect.top, null); canvas.drawBitmap(mBGBitmap, mBGgmatrix, null); // 畫圖片 canvas.save(Canvas.ALL_SAVE_FLAG); // 儲存畫布 canvas.restore(); Bitmap ret = Bitmap.createBitmap(tmpBitmap, mFloatRect.left, mFloatRect.top, mFloatRect.width(), mFloatRect.height(), null, true); tmpBitmap.recycle(); tmpBitmap = null; Bitmap newRet = Bitmap.createBitmap(mFloatRect.width(), mFloatRect.height(), Config.ARGB_8888); Canvas canvasHead = new Canvas(newRet); canvasHead.drawBitmap(ret, 0, 0, null); Paint paintHead = new Paint(); paintHead.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); Bitmap crop = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.headmask); canvasHead.drawBitmap(crop, 0, 0, paintHead); return newRet;
效果
***基本上我不提供原始碼,但是我會盡量用文字把對應的演算法描述清楚****因為靠自己的努力和實踐寫出來的效果才真正是自己的東西如果想要源碼Demo,請聯絡我