Android自定义刮刮乐控件

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;
    }
}




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值