要求
根据给定的头部模板,截取资源图。背景图可支持拖动,缩放,拖动旋转
分析
定义剪切浮层,实现背景资源图的操作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,请联系我