Android Scratch Card

Source: Internet
Author: User

Haven't written a blog for a long time, today there is just a moment, next for everyone to bring an e-commerce to use the scratch card project, scraping card I believe we all played, that time, may be used to be small paper, and now also can take everyone to relive the good times of childhood, today will this scratch card project to share to everyone, Hope to have a study and work on the help.


One: first.






Second: Principle analysis

1. Create a bitmap size you want, then draw a canvas on top of the bitmap size, then rewrite the OnDraw () method

2. In the continuous expansion of the scraping area, the size of the expansion surface is calculated, when the area exceeds 60%, it is clear that the layer

3. The following scraping card information, you can use the random number in Java to do, it is a multiple of 900 what, before winning, this random play


Three: Source code example


Custom Control Code:

Package Com.zengtao.view;import Android.annotation.suppresslint;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.graphics.paint.style;import Android.graphics.path;import Android.graphics.porterduffxfermode;import Android.graphics.rect;import Android.os.handler;import Android.os.message;import Android.util.attributeset;import Android.util.log;import android.view.MotionEvent; Import android.view.view;/** * Scratch card * * @author Zengtao April 17, 2015 Morning 11:13:46 */@SuppressLint ("drawallocation") public clas S Guaguaka extends View {//-------1. Something in the cover layer private int lastx;private int lasty;private int height = 300;private int width = 120;private int movingx;private int movingy;private Bitmap mbitmap;private Paint mpaint;private Canvas mcanvas;private P Ath mpath;//--------2. Something under the cover layer private String mtext;private Paint mtextpaint;private int mtextsize;private Rect Mrectbounds; Get Scratch award information for width and height pRivate int[] mpixels;private volatile Boolean iscomlemete = False;private Message msg;private Setonguaguacomplemetelistener mguaguacomplemetelistener;public void Setonguaguacomplemetelistener ( Setonguaguacomplemetelistener mguaguacomplemetelistener) {This.mguaguacomplemetelistener = Mguaguacomplemetelistener;} Public Guaguaka (Context context) {super (context); init (context);} Public Guaguaka (context context, AttributeSet Attrs) {Super (context, attrs); init (context);} @SuppressLint ("drawallocation") @Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) { Super.onmeasure (Widthmeasurespec, heightmeasurespec);//1.1 Get the height and width of width = measurespec.getsize (widthmeasurespec); Height = measurespec.getsize (heightmeasurespec);//1.2 Get wide height at initialization bitmapmbitmap = bitmap.createbitmap (width, height, Bitmap.Config.ARGB_8888); Mcanvas = new Canvas (MBITMAP);//1.3 Sets the properties of the drawing path Brush SetPath ();//2.1 Set Textpaint property Settextmessagepaint (); Mcanvas.drawcolor (Color.parsecolor ("#C7C7C7"));} @SuppressLint ("ClickablevIewaccessibility ") @Overridepublic boolean ontouchevent (Motionevent event) {MOVINGX = (int) event.getx (); movingy = (int) Event.gety (); switch (Event.getaction ()) {Case MotionEvent.ACTION_DOWN:touchDown (event); break;case MotionEvent.ACTION_MOVE:touchMove (event); Break;case MotionEvent.ACTION_UP:touchUp (event); break;default:break;} Invalidate (); return true;} @Overrideprotected void OnDraw (canvas canvas) {canvas.drawtext (MText, getwidth ()/2-mrectbounds.width ()/2,getheight ( )/2 + mrectbounds.height ()/2, Mtextpaint), if (!iscomlemete) {DrawPath (); Canvas.drawbitmap (mbitmap, 0, 0, null);}} Draw pathprivate void DrawPath () {Mpaint.setxfermode (new Porterduffxfermode (Android.graphics.PorterDuff.Mode.DST_OUT ); Mcanvas.drawpath (MPath, mpaint);} Gesture lifted private void touchUp (Motionevent event) {new Thread (mrunnable). Start ();}  Gesture down private void TouchMove (Motionevent event) {int dx = Math.Abs (movingx-lastx); int dy = Math.Abs (movingy-lasty); if (dx > 3 | | dy > 3) {Mpath.lineto (MOVINGX, movingy);} LASTX = Movingx;lasty = movingy;} Gestures Press private void TouchDown (Motionevent event) {lastx = Movingx;lasty = Movingy;mpath.moveto (Lastx, lasty);} /** * Set the properties of the drawing path brush */private void SetPath () {Mpaint.setcolor (Color.parsecolor ("#c0c0c0")); Mpaint.setantialias (True) ; Mpaint.setdither (true); Mpaint.setstrokejoin (Paint.Join.ROUND); Mpaint.setstrokecap (Paint.Cap.ROUND); Mpaint.setstyle (Paint.Style.STROKE); Mpaint.setstrokewidth (40);} /** * Set the properties of the scratch card brush */private void Settextmessagepaint () {mtextpaint.setcolor (Color.dkgray); Mtextpaint.settextsize ( mtextsize); Mtextpaint.setstyle (Style.fill);//Gets the current brush drawing text width and height mtextpaint.gettextbounds (mText, 0, Mtext.length (), Mrectbounds);}  /** * Initialize * * @param context */private void init (Context context) {//----1. Cover Layer mpaint = new Paint (); mPath = new Path ();// ----2. Content under the overlay mtextpaint = new Paint (); mrectbounds = new Rect (); mText = "Thank you"; mtextsize = 40;} /** * Turn on thread count user erased how many areas */private Runnable mrunnable = new Runnable () {@Overridepublic void run () {int w = getwidth (); int h = getheight (); float Wipearea = 0;float Totalarea = w * h; Bitmap Bitmap = mbitmap;if (mpixels = = null) {mpixels = new int[w * h];} Get all the pixel information on bitmap bitmap.getpixels (mpixels, 0, W, 0, 0, W, h); for (int i = 0; i < W; i++) {for (int j = 0; J < H; j + +) {int index = i + J * W;IF (mpixels[index] = = 0) {wipearea++;}}} if (Wipearea > 0 && totalarea > 0) {int percent = (int) (Wipearea * 100/totalarea); LOG.E ("System.out", "area---" + percent),//Qingchutu layer area if (Percent >) {iscomlemete = True;postinvalidate ();} If the user is not allowed to do this in a child thread while calling the toast, the case belongs to the new UI in the child thread, so use handle to manipulate MSG = Mhandler.obtainmessage () in the main thread; msg.what = 0x1; MSG.ARG1 = Percent;mhandler.sendmessage (msg);}}; @SuppressLint ("Handlerleak") private Handler Mhandler = new Handler () {public void Handlemessage (Message msg) {if (Mguagua Complemetelistener! = null) {int percent = Msg.arg1;if (Percent <) {Mguaguacomplemetelistener.notenough ("Pro, you're scraping, It's not enough! 55555 ");} else {mguaguacomplemetelistener.complemete (mText);}}};}; Public Interface Setonguaguacomplemetelistener {void Complemete (string result); void Notenough (string result);}} 


Two: the realization in mainactivity

Package Com.zengtao.testdemo;import Android.app.activity;import Android.os.bundle;import Android.widget.Button; Import Android.widget.toast;import Com.zengtao.view.guaguaka;import Com.zengtao.view.guaguaka.setonguaguacomplemetelistener;public class Mainactivity extends Activity {private Guaguaka Mguaguaka;private Button reStart; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); Mguaguaka = (Guaguaka) Findviewbyid (R.id.scratch); ReStart = (Button) Findviewbyid (R.id.restart); Mguaguaka.setonguaguacomplemetelistener (new Setonguaguacomplemetelistener () {@Overridepublic void Complemete (String result) {Toast.maketext (Mainactivity.this, result, Toast.length_short). Show ();} @Overridepublic void Notenough (String result) {Toast.maketext (mainactivity.this, result, Toast.length_short). Show ();}});}}


Four: The above can be completed scraping card implementation, looking at or is quite simple, then you also try it, mosquitoes, although small, but also meat, to take it


Demo:http://download.csdn.net/detail/u011546655/8617235


Android Scratch Card

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.