1 PackageCom.example.administrator.mystudent.surfaceView;2 3 ImportAndroid.content.Context;4 ImportAndroid.graphics.Canvas;5 ImportAndroid.graphics.Color;6 ImportAndroid.graphics.Paint;7 ImportAndroid.graphics.Rect;8 ImportAndroid.util.AttributeSet;9 ImportAndroid.view.SurfaceHolder;Ten ImportAndroid.view.SurfaceView; One A /** - * Created by Administrator on 2016/9/13. - */ the Public classTestsufaceviewextendsSurfaceviewImplementsSurfaceholder.callback { - - PrivateSurfaceholder Holder; - PrivateMyThread MyThread; + - PublicTestsufaceview (Context context) { + Super(Context,NULL); A } at - PublicTestsufaceview (Context context, AttributeSet attrs) { - Super(context, attrs); - -Holder = This. Getholder (); -Holder.addcallback ( This); inMyThread =NewMyThread (holder);//create a drawing thread - to } + - the /** * * @paramHolder is fired when it is created and is typically called here to draw the thread $ */Panax Notoginseng @Override - Public voidsurfacecreated (Surfaceholder holder) { the +Mythread.isrun =true; A Mythread.start (); the } + - /** $ * @paramHolder $ * @paramformat - * @paramwidth - * @paramheight fires when the size of your surface changes the */ - @OverrideWuyi Public voidSurfacechanged (Surfaceholder holder,intFormatintWidthintheight) { the - } Wu - /** About * @paramholder fires when destroyed, typically where a drawing thread is stopped, released $ */ - @Override - Public voidsurfacedestroyed (Surfaceholder holder) { - AMythread.isrun =false; + } the - //thread Inner class $ classMyThreadextendsThread { the PrivateSurfaceholder Holder; the Public BooleanIsrun; the the PublicMyThread (Surfaceholder holder) { - This. Holder =Holder; inIsrun =true; the } the About @Override the Public voidrun () { the intCount = 0; the while(isrun) { +Canvas C =NULL; - Try { the synchronized(Holder) {Bayic = Holder.lockcanvas ();//Lock the canvas, usually after it is locked, it can be drawn through canvas objects it returns, drawing on it, and so on. theC.drawcolor (Color.Black);//set the canvas background color thePaint p =NewPaint ();//Create a brush - P.setcolor (color.white); -Rect r =NewRect (100, 50, 300, 250); the C.drawrect (R, p); theC.drawtext ("This is the first" + (count++) + "seconds", 100, 310, p); theThread.Sleep (1000);//sleep time is 1 seconds the } - } the Catch(Exception e) { the e.printstacktrace (); the}finally94 { the if(c! =NULL) the { theHolder.unlockcanvasandpost (c);//end the lock drawing and commit the change. 98 } About } - }101 }102 103 }104}
Simple use of Surfaceview