"2014 Last share" Android implementation custom Scratch card effect view

Source: Internet
Author: User

First, Introduction:

Today is the last day of 2014, first here, I wish you all in the new 2015 years of new health, new income, new smooth, new Ruyi!!!

On the previous page, I introduced the blog "Android implementation custom round, fillet and Ellipse imageview (using the Xfermode Graphics rendering method)" Using Xfermode to implement custom fillet and ellipse picture view.

Today we take a look at how to achieve the e-commerce app commonly used in the scratch card effect of the view component, in fact, the principle and the realization of a rounded picture of the similar, are using the Xfermode rendering mode to achieve.

(The usual, the source at the end of the blog to give ha)

The fundamental steps are this:

1. Draw the lower layer (i.e. the DST layer) first, that is: Scratch card background layers

2. Set Xfermode mode to Dst_out

3. Draw the path of the sweep, draw the upper

This through the three steps, you can achieve the effect of scraping card, because the use of Dst_out mode, which is to take the upper and lower layers of the intersection of the lower part, let us look at the specific effect of it

Two:

Three, Xfermode rendering mode introduction:

Xfermode affects how new colors are drawn on canvas-already-existing images
* Under normal circumstances, draw a new shape on the image, and if the new paint is not transparent, it will obscure the color below.
* If the new paint is transparent, it will be dyed to the following color

The following subclass of Xfermode can change this behavior:

AVOIDXFERMODE specifies a color and tolerance, forcing paint to avoid drawing on it (or just drawing on it).

Pixelxorxfermode a simple pixel XOR operation is applied when the existing color is overwritten.

Porterduffxfermode This is a very powerful conversion mode, using it, you can use any of the 16 porter-duff rules of the image composition to control how paint interacts with existing canvas images.

I have to mention the classic picture here:

The above 16 modes are described below:

From the above we can see that Porterduff.mode is an enumeration class with a total of 16 enumeration values:

1.porterduff.mode.clear

The drawing is not submitted to the canvas.
2.porterduff.mode.src

Show Top Draw picture
3.porterduff.mode.dst

Show Lower drawing pictures
4.porterduff.mode.src_over

Normal drawing shows that the upper and lower layers are drawn with overlapping covers.
5.porterduff.mode.dst_over

The upper and lower layers are displayed. The lower level is shown on the home.
6.porterduff.mode.src_in

Draw the intersection of two layers. Displays the upper layer.
7.porterduff.mode.dst_in

Draw the intersection of two layers. Displays the lower layer.
8.porterduff.mode.src_out

Draw the non-intersecting portion of the upper layer.
9.porterduff.mode.dst_out

Remove the layer to draw the non-intersecting part.
10.porterduff.mode.src_atop

Remove the non-intersecting part of the layer from the upper intersection section
11.porterduff.mode.dst_atop

Take the upper non-intersecting part and the lower part of the intersection
12.porterduff.mode.xor

XOR: Remove the two Layer intersection section
13.porterduff.mode.darken

Take two layers of all areas, the intersection part of the color deepened
14.porterduff.mode.lighten

Take two layers all, light the intersection part color
15.porterduff.mode.multiply

Take two layer intersection part overlay color
16.porterduff.mode.screen

Take two layers of all areas, the intersection part becomes transparent color

Iv. Customizing the Scratch Card effect view component implementation:

1. Draw the underlying background layer

@Overrideprotected voidOnmeasure (intWidthmeasurespec,intHeightmeasurespec) {        //TODO auto-generated Method Stub        Super. Onmeasure (Widthmeasurespec, Heightmeasurespec); intwidth =getmeasuredwidth (); intHeight =getmeasuredheight (); //Initialize bitmapMbitmap =bitmap.createbitmap (width, height, config.argb_8888); //Initialize CanvasMcanvas =NewCanvas (MBITMAP); //set some properties of a brushSetoutterpaint ();        Setoutbmppaint ();        Settextpaint (); //draw a scratch card fillet background layerMcanvas.drawroundrect (NewRECTF (0,0,width,height), 30, 30, Moutbmppaint); Mcanvas.drawbitmap (Moutterbitmap,NULL,NewRECTF (0,0,width,height),NULL); }

2. Set the Xfermode mode and draw the upper path layer

/**      * Set Xfermode mode to Dst_out, and draw the path     of the sweep *    /privatevoid  DrawPath () {         // TODO auto-generated Method Stub                 Moutterpaint.setxfermode (new  Porterduffxfermode (mode.dst_out));                Mcanvas.drawpath (MPath, moutterpaint);    }

3. Finally draw it out in OnDraw:

@Overrideprotected voidOnDraw (canvas canvas) {//TODO auto-generated Method Stub//Draw TextCanvas.drawtext (MText, GetWidth ()/2-mtextbound.width ()/2, GetHeight ()/2+mtextbound.height ()/2, Mtextpaint); //Wiper Completion Callback        if(mcompleted) {if(NULL!=Moncompletelistener)            {Moncompletelistener.complete (); }        }        //decide whether to complete and not draw the cover layer if finished        if(!mcompleted)            {DrawPath (); Canvas.drawbitmap (Mbitmap,0,0,NULL); }    }

4. Gesture Touch Recording Path implementation:

@Override Public Booleanontouchevent (Motionevent event) {//TODO auto-generated Method Stub        intAction =event.getaction (); intx = (int) Event.getx (); inty = (int) event.gety (); Switch(action) { CaseMotionEvent.ACTION_DOWN:mLastX=x; Mlasty=y;                                Mpath.moveto (MLASTX, mlasty);  Break;  CaseMotionevent.action_move:intDX = Math.Abs (X-mlastx); intdy = Math.Abs (Y-mlasty); if(dx >3 | | dy > 3) {Mpath.lineto (x, y); } mlastx=x; Mlasty=y;  Break;  Casemotionevent.action_up:NewThread (mrunnable). Start ();  Break; default:                 Break;        } invalidate (); return true; }

5. The calculation of the area of the sweep area and the implementation of the scraping finish, in order to not affect the drawing, the part is implemented in the sub-thread alone

/*** Start a thread to calculate the area that has been swept and the percentage of the total area * Depending on the region to determine whether to complete*/    PrivateRunnable mrunnable =NewRunnable () {@Override Public voidrun () {intW =getwidth (); inth =getheight (); floatWipearea = 0; floatTotalarea = w *h; Bitmap Bitmap=Mbitmap; int[] Mpixels =New int[w *h]; //get all pixel information for bitmapBitmap.getpixels (mpixels, 0, W, 0, 0, W, h);  for(inti= 0; i< w;i++)                 for(intj= 0; j< h;j++){                    intindex = i + j *W; if(Mpixels[index] = = 0) {Wipearea++; }                }            //calculate the proportion of swept areas            if(Wipearea >0 && totalarea > 0){                intPercent = (int) (Wipearea * 100/Totalarea); LOG.V ("Czm", "percent=" +percent); if(Percent > 70){                    //Clear Layer Areamcompleted =true;                                    Postinvalidate ();    }            }        }; };

This is where the core module code of the custom scratch card effect view is introduced. Here's a look at the implementation of the layout using the view, which is very simple.

v. implementation of the view layout

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:id=" @+id/container "    android:layout_width=" Match_ Parent "    android:layout_height=" Match_parent ">        <com.czm.xcguaguaka.XCGuaguakaView        android:id= "@+id/ggk"        android:layout_width= "300DP"    android:layout_height = "100DP"    android:layout_centerinparent= "true"/>    </RelativeLayout>

Vi. using and testing a custom scratch card effect view

The custom view that was drawn directly above is finished, and the following is the use of this custom view, which, like normal view, is used as a normal control.

 PackageCom.czm.xcguaguaka;ImportCom.czm.xcguaguaka.XCGuaguakaView.OnCompleteListener;Importandroid.app.Activity;ImportAndroid.app.ActionBar;Importandroid.app.Fragment;ImportAndroid.os.Bundle;ImportAndroid.view.LayoutInflater;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.Toast;ImportAndroid.os.Build;/*** Use and test the custom scratch card effect View *@authorcaizhiming **/ Public classMainactivityextendsActivity {PrivateXcguaguakaview Xcguaguakaview; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Xcguaguakaview=(Xcguaguakaview) Findviewbyid (R.ID.GGK); Xcguaguakaview.setoncompletelistener (NewOncompletelistener () {@Override Public voidComplete () {//TODO auto-generated Method StubToast.maketext (Getapplicationcontext (), "You've shaved almost.", Toast.length_short). Show ();    }        }); }}

Seven, as usual, finally provide full source download

Real Theme Park net :http://www.zhentiyuan.com

Source Download :http://download.csdn.net/detail/jczmdeveloper/8317629

"2014 Last share" Android implementation custom Scratch card effect view

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.