Realization of the Surfaceviewdemo of the turntable lottery

Source: Internet
Author: User

Reference: http://www.cnblogs.com/xuling/archive/2011/06/06/android.html

Surfaceview is the inheritance class for view, which has a built-in surface for drawing. You can control the format and size of this surface. Surfaceview controls where this surface is drawn.

Surface is a deep sort (z-ordered), which indicates that it is always behind its own window. The Surfaceview provides a visible area that is visible only on the surface portion of the visible area and not visible outside the visible area. The layout display of surface is affected by the view hierarchy, and its sibling view nodes are displayed at the top. This means that the content of surface is obscured by its sibling view, which can be used to place a cloak (overlays) (for example, text and buttons). Note that if you have transparent controls on your surface, each change will cause the framework to recalculate the transparency of its and top-level controls, which can affect performance.
You can get this interface by accessing the Surface,getholder () method through the Surfaceholder interface.
Surface is created when Surfaceview becomes visible, and surface is destroyed before Surfaceview is hidden. This will save resources. If you want to see when your surface is created and destroyed, you can reload surfacecreated (Surfaceholder) and surfacedestroyed (Surfaceholder).
The core of Surfaceview is the provision of two threads: the UI thread and the render thread. It should be noted here:
1> all methods of Surfaceview and Surfaceholder.callback should be called in the UI thread, which is generally the main thread of the application. The various variables to be accessed by the render thread should be processed synchronously.

2> because surface may be destroyed, it is only valid between SurfaceHolder.Callback.surfaceCreated () and SurfaceHolder.Callback.surfaceDestroyed (), So make sure that the rendering thread is accessing the legitimate, effective surface.

——————————————————————————————————————————————————————————————————————————

The use of Surfaceview is much used in game development. and a generic template for Surfaceview is the following code:

Surfacetemplate.java

Package Com.example.surfaceviewdemo;import Android.content.context;import Android.graphics.canvas;import Android.util.attributeset;import Android.view.surfaceholder;import Android.view.surfaceholder.callback;import Android.view.surfaceview;public class Surfacetemplate extends Surfaceview implements Callback, Runnable {private Surfaceholder mholder;private Canvas mcanvas;/** * For drawing threads */private thread t;/** * Threading Control Switch */private Boolean ISRUNNING;PU Blic surfacetemplate (Context context) {this (context,null);} Public Surfacetemplate (context context, AttributeSet Attrs) {Super (context, attrs); mholder = Getholder (); Mholder.addcallback (this);//Can get focus setfocusable (TRUE); Setfocusableintouchmode (true);//Set constant Setkeepscreenon (true);} @Overridepublic void surfacecreated (Surfaceholder holder) {isrunning = true;//initializes the thread after surface creation, opening the thread. t = new Thread (this); T.start ();} @Overridepublic void Surfacechanged (surfaceholder holder, int format, int width,int height) {} @Overridepublic void Surfac Edestroyed (SurfaceholDer Holder) {isrunning = false;} @Overridepublic void Run () {while (isrunning) {//Keep drawing Draw ();}} private void Draw () {try{//gets canvasmcanvas = Mholder.lockcanvas (); if (Mcanvas! = null) {}}catch (Exception e) {}finally{if (Mcanvas! = null) {mholder.unlockcanvasandpost (Mcanvas);}}}}

The following is a case of surfaceview, according to the course of the online tutorial, I knocked over the code to get up. This is a custom view of a carousel draw, video address in: http://www.imooc.com/learn/444

is the project catalog structure diagram:



The code for Mainactivity.java is as follows:

</pre><pre name= "code" class= "java" >package com.example.surfaceviewdemo;import android.app.Activity; Import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.imageview;public class Mainactivity extends Activity {private Luckypan mluckypan;private ImageView mstartbtn; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Mluckypan = (Luckypan) Findviewbyid (r.id.id_luckypan); mStartBtn = (ImageView ) Findviewbyid (R.ID.ID_START_BTN); Mstartbtn.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick ( View v) {if (! Mluckypan.isstart ()) {Mluckypan.luckystart (); Mstartbtn.setimageresource (r.drawable.stop);} Else{if (! mluckypan.isshouldend ()) {mluckypan.luckyend (); Mstartbtn.setimageresource (R.drawable.start);}}});}}

The code for Luckypan.java is as follows:

Package Com.example.surfaceviewdemo;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.graphics.paint;import Android.graphics.path;import Android.graphics.rect;import Android.graphics.rectf;import Android.util.AttributeSet ; import Android.util.typedvalue;import Android.view.surfaceholder;import android.view.SurfaceHolder.Callback; Import Android.view.surfaceview;import Android.widget.toast;public class Luckypan extends Surfaceview implements Callback, Runnable {private Surfaceholder mholder;private Canvas mcanvas;/** * used to draw thread */private thread t;/** * Thread control switch */ Private Boolean isrunning;/** * An array of various prizes in the Sweepstakes Carousel */private string[] mstrs = new string[]{"SLR Camera", "IPAD", "Congratulations to Fortune", "IPHONE", " Costume set "," Congratulations on getting rich "};/** * the picture array needed in the draw Carousel */private int[] Mimgs = new Int[]{r.drawable.p_danfan,r.drawable.p_ipad, r.drawable.p_xiaolian,r.drawable.p_iphone,r.drawable.p_meizi,r.drawable.p_xiaolian};/** * Each disk block corresponds to the color, which only two colors, But alternating with each other。 */private int[] mcolors = new int[]{0xffffc300,0xfff17e01,0xffffc300,0xfff17e01,0xffffc300,0xfff17e01};/** * Number corresponding to the disk block. */private int mitemcount = 6;/** * The bitmap array corresponding to the picture, followed by Mimgs in the drawable array to initialize bitmap. */private bitmap[] Mimgsbitmap/** * Background image Bitmap */private Bitmap mbgbitmap = Bitmapfactory.decoderesource (getResources (), r.drawable.bg2);/** * The range of the entire disk block, expressed as a rectangle. */private RECTF mrange = new RECTF ();/** * diameter of entire disk block */private int mradius;/** * Draw disk block Brush */private paint marcpaint;/** * Draw Text This brush */private paint mtextpaint;/** * Font size */private float mtextsize = typedvalue.applydimension (typedvalue.complex_ UNIT_SP, Getresources () getdisplaymetrics ())/** * Disk block rotation speed */private double mspeed;/** * */private volatile int MStar Tangle = 0;//in order to ensure the visibility between threads, it needs to be declared with volatile. /** * Determine if the Stop button is clicked */private Boolean isshouldend;/** * Center position of the turntable */private int mcenter;/** * The mpadding here directly takes the minimum value in four padding, or Direct to paddingleft */private int mpadding;p ublic Luckypan (Context context) {this (context,null);} Public LuckYpan (context context, AttributeSet Attrs) {Super (context, attrs); mholder = Getholder (); Mholder.addcallback (this);// Can get focus setfocusable (TRUE); Setfocusableintouchmode (true);//Set constant Setkeepscreenon (true);} @Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasurespec, HEIGHTMEASURESPEC); int width = math.min (Getmeasuredwidth (), Getmeasuredheight ()); Mradius = Width-getpaddingleft () * 2; mpadding = Getpaddingleft (); Toast.maketext (GetContext (), "" + mpadding, Toast.length_short). Show ();//Diameter Mradius = width-mpadding * 2;//Center Point mcenter = w Idth/2;setmeasureddimension (width, width);} @Overridepublic void surfacecreated (Surfaceholder holder) {//Initialize the brush that draws the disk block marcpaint = new paint (); Marcpaint.setantialias (true); Marcpaint.setdither (true);//Initialize the brush mtextpaint = new paint (); Mtextpaint.setcolor (0xFFFFFFFF) of the drawing disk block; Mtextpaint.settextsize (mtextsize);//Initialize disk block drawing range Mrange = new RECTF (mpadding, mpadding, mpadding + Mradius, mpadding + Mradius);//Initialize picture Mimgsbitmap = new Bitmap[Mitemcount];for (int i = 0;i < Mitemcount; i++) {Mimgsbitmap[i] = Bitmapfactory.decoderesource (Getresources (), mImgs[ I]);} IsRunning = true;//Initializes the thread after the surface is created and opens the thread. t = new Thread (this); T.start ();} @Overridepublic void Surfacechanged (surfaceholder holder, int format, int width,int height) {} @Overridepublic void Surfac Edestroyed (Surfaceholder holder) {isrunning = false;} @Overridepublic void Run () {while (isrunning) {Long start = System.currenttimemillis ();//draws draw () continuously; long end = System.currenttimemillis (), if (End-start <) {try {thread.sleep (end-start);} catch (Interruptedexception e) {e.printstacktrace ();}}}} private void Draw () {try{//gets canvasmcanvas = Mholder.lockcanvas (), if (Mcanvas! = null) {//Draw background drawbg ();//Draw disk block float Tmpangle = Mstartangle;float SweepAngle = 360/mitemcount;for (int i = 0; i < Mitemcount; i++) {Marcpaint.setcolor (mcolors [i]); /Draw a disk block Mcanvas.drawarc (Mrange, Tmpangle, SweepAngle, True, marcpaint);//Draw Text DrawText (Tmpangle,sweepangle,mstrs[i]) ;//Draw the picture on the disk block DRawicons (Tmpangle,mimgsbitmap[i]); Tmpangle + = SweepAngle;} Mstartangle + = mspeed;//If you click the Stop button if (isshouldend) {mspeed-=1;} if (mspeed <= 0) {mspeed = 0;isshouldend = false;}}} catch (Exception e) {}finally{if (Mcanvas! = null) {mholder.unlockcanvasandpost (Mcanvas);}}} /** * Click Start rotation */public void Luckystart () {mspeed = 50;isshouldend = false;} public void Luckyend () {isshouldend = true;} /** * Whether the turntable is rotated */public boolean isstart () {return mspeed! = 0;} public Boolean isshouldend () {return isshouldend;} /** * Draw picture on disk block * @param bitmap * @param tmpangle */private void drawicons (float tmpangle, bitmap bitmap) {//Set the width of the picture to diameter 1/8;int ImgWidth = mradius/8;float angle = (float) ((Tmpangle + 360/mitemcount/2) * math.pi/180); int x = (int) (Mcente R + MRADIUS/2/2 * Math.Cos (angle)); int y = (int) (Mcenter + MRADIUS/2/2 * Math.sin (angle));//Determine the position of the picture rect rect = new Rect ( X-IMGWIDTH/2, Y-IMGWIDTH/2, x + imgwidth/2, y + imgwidth/2); Mcanvas.drawbitmap (bitmap, NULL, rect, NULL);} /** * Draw the text of each disk block * @param tmpangle * @Param sweepAngle * @param mStrs2 */private void DrawText (float tmpangle, float sweepAngle, string string) {Path PATH = new Path ();p Ath.addarc (Mrange, Tmpangle, sweepAngle);//Use horizontal offset to center text in float textWidth = Mtextpaint.measuretext (string); int Hoffset = (int) ((Mradius * math.pi/mitemcount/2)-(TEXTWIDTH/2)); int vOffset = mradius/2/6;//vertical offset mcanvas.drawt Extonpath (String, Path, Hoffset, VOffset, Mtextpaint); /** * Draw background */private void Drawbg () {mcanvas.drawcolor (0xFFFFFFFF); Mcanvas.drawbitmap (Mbgbitmap, NULL, new Rect (mpadding /2,mpadding/2,getmeasuredwidth ()-Mpadding/2,getmeasuredheight ()-MPADDING/2), NULL);}}

Activity_main.xml

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    tools:context= ". Mainactivity ">    <com.example.surfaceviewdemo.luckypan         android:id=" @+id/id_luckypan "        android: Layout_width= "Match_parent"        android:layout_height= "match_parent"        android:layout_centerinparent= "true"        android:padding= "30DP"        /><imageview     android:id= "@+id/id_start_btn"    android:layout_ Width= "Wrap_content"    android:layout_height= "wrap_content"    android:layout_centerinparent= "true"    android:src= "@drawable/start"    />    </RelativeLayout>

The source address is: Http://pan.baidu.com/s/1eSFMwzK



Realization of the Surfaceviewdemo of the turntable lottery

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.