Android刮刮乐控件可以利用Xfermode以及PorterDuff来实现,PorterDuff的16种参数效果如下:
代码如下:
public class GuaView extends View {
private Paint mPaint=new Paint();
private Path mPath = new Path();
private Bitmap bitMapForDraw;
private Canvas canvas;
private int mLastX;
private int mLastY;
public GuaView(Context context)
{
super(context);
}
public GuaView(Context context, AttributeSet attributeSet)
{
super(context, attributeSet);
}
public GuaView(Context context, AttributeSet attributeSet, int defStyle)
{
super(context, attributeSet, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width=getMeasuredWidth();
int height=getMeasuredHeight();
bitMapForDraw=Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
canvas=new Canvas(bitMapForDraw);
mPaint.setAntiAlias(true);
mPaint.setColor(Color.DKGRAY);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(20);
canvas.drawARGB(255, 56, 105, 199);
}
@Override
protected void onDraw(Canvas canvas) {
String text="谢谢参与";
float textSize=60.0f;
Paint p=new Paint();
p.setAntiAlias(true); p.setDither(true);
p.setColor(Color.CYAN); p.setTextSize(textSize);
p.setStyle(Paint.Style.STROKE);
float len = p.measureText(text);
float xPos=(getMeasuredWidth()-len)/2;
float yPos=getMeasuredHeight()/2;
canvas.drawText(text, xPos, yPos, p);
renderToBitmap();
canvas.drawBitmap(bitMapForDraw, 0, 0, null);
}
private void renderToBitmap()
{
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
canvas.drawPath(mPath, mPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x=(int)event.getX();
int y=(int)event.getY();
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN: {
mLastX=x;
mLastY=y;
mPath.moveTo(x, y);
break;
}
case MotionEvent.ACTION_MOVE: {
mPath.lineTo(x, y);
break;
}
default:
break;
}
invalidate();
return true;
}
}