安卓开发之刮刮乐实例教程
刮奖在生活中常常见到,网上现在也有各种各样的抽奖活动,下面我们就要实现一个刮刮乐程序,可以完美满足 大家的虚荣心,哈哈,下面就开始吧,100%中奖的喔!
下面先来看看效果图:
让我们来看看它的布局:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
< RelativeLayout android:layout_width = "match_parent" android:layout_height = "match_parent" > < TextView android:id = "@+id/textView1" android:layout_width = "300dp" android:layout_height = "150dp" android:layout_centerHorizontal = "true" android:layout_centerVertical = "true" android:background = "@android:color/holo_red_dark" android:gravity = "center" android:text = "恭喜你,中奖啦!" android:textSize = "35dp" /> < net.androidchina.example.guale.EraseView android:id = "@+id/eraseView1" android:layout_width = "300dp" android:layout_height = "150dp" android:layout_centerHorizontal = "true" android:layout_centerInParent = "true" android:layout_centerVertical = "true" /> </ RelativeLayout > |
布局很简单,通过相对布局,将文字和view重叠到一起,重点是EraseView这个类的实现,下面一起看看这个类的代码:
首先我们要定义一个画布以及画笔
1
2
3
4
5
6
7
8
9
10
|
paint = new Paint(); paint.setStyle(Paint.Style.STROKE); paint.setXfermode( new PorterDuffXfermode(Mode.CLEAR)); paint.setAntiAlias( true ); paint.setDither( true ); paint.setStrokeJoin(Paint.Join.ROUND); paint.setStrokeCap(Paint.Cap.ROUND); paint.setStrokeWidth( 30 ); mCanvas = new Canvas(bitmap); |
当手指触摸屏幕时,需要触发滑动事件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@Override public boolean onTouchEvent(MotionEvent event) { float ax = event.getX(); float ay = event.getY(); if (event.getAction() == MotionEvent.ACTION_DOWN) { isMove = false ; path.reset(); path.moveTo(ax, ay); invalidate(); return true ; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { isMove = true ; path.lineTo(ax, ay); invalidate(); return true ; } return super .onTouchEvent(event); } |
这里需要一个path来记录轨迹,并且需要调用invalidate();来对画布进行重画,会进一步调用onDraw方法:
1
2
3
4
5
6
7
8
9
10
|
@Override protected void onDraw(Canvas canvas) { if (mCanvas == null ) { EraseBitmp(); } canvas.drawBitmap(bitmap, 0 , 0 , null ); mCanvas.drawPath(path, paint); super .onDraw(canvas); } |
源码下载:点击下载