Implement a simple drawing tool: (You can draw any in the view, click the Clear button, you can redraw, like I draw you guess)
Custom View Code:
Public classMySurfaceView2extendsSurfaceviewImplementsSurfaceholder.callback, View.ontouchlistener {PrivatePath MPath =NewPath (); PrivatePaint Mpaint =NewPaint (); PublicMySurfaceView2 (Context context) {Super(context); Init (); } PublicMySurfaceView2 (Context context, AttributeSet attrs) {Super(context, attrs); Init (); } Private voidinit () {Setontouchlistener ( This); Getholder (). Addcallback ( This); } Public voidDraw () {canvas Canvas=Getholder (). Lockcanvas (); Canvas.drawcolor (Color.White); Canvas.drawpath (Mpath,mpaint); Getholder (). Unlockcanvasandpost (canvas); } //clean up the canvas Public voidClear () {mpath.reset (); Draw (); } @Override Public voidsurfacecreated (Surfaceholder surfaceholder) {} @Override Public voidSurfacechanged (Surfaceholder Surfaceholder,intIintI1,intI2) {Draw (); } @Override Public voidsurfacedestroyed (Surfaceholder surfaceholder) {} @Override Public BooleanOnTouch (view view, Motionevent motionevent) {Switch(Motionevent.getaction ()) { CaseMotionEvent.ACTION_DOWN:mPaint.setStyle (Paint.Style.STROKE); Mpaint.setcolor (color.red); Mpath.moveto (Motionevent.getx (), motionevent.gety ()); Break; CaseMotionevent.action_move://Generate linesMpath.lineto (Motionevent.getx (), motionevent.gety ()); Draw (); Break; } return true; }}
To load a custom view in XML:
<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:app= "Http://schemas.android.com/apk/res-auto"android:orientation= "vertical"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"> <com. Example.lance.test2.MySurfaceView2 Android:id= "@+id/my_surface"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:layout_weight= "1"/> <ButtonAndroid:id= "@+id/btn"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Clear"/></LinearLayout>
In the main activity code:
Public classMainactivityextendsappcompatactivity {PrivateMySurfaceView2 mMySurfaceView2; PrivateButton Mbutton; @Overrideprotected voidonCreate (@Nullable Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.four); MMySurfaceView2=(MYSURFACEVIEW2) Findviewbyid (r.id.my_surface); Mbutton=(Button) Findviewbyid (R.ID.BTN); Mbutton.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (view view) {mmysurfaceview2.clear (); } }); }}
Use of path in Android