PackageCom.pingyijinren.helloworld;ImportAndroid.content.Context;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Color;ImportAndroid.graphics.Paint;ImportAndroid.graphics.Point;ImportAndroid.util.AttributeSet;Importandroid.view.MotionEvent;ImportAndroid.view.View;Importjava.util.ArrayList;ImportJava.util.Iterator;/*** Created by Administrator on 2016/6/2 0002.*/ Public classMypaintviewextendsView {PrivateArraylist<point> allpoints=NewArraylist<point>(); PublicMypaintview (Context context, AttributeSet attrs) {Super(context, attrs); SetBackgroundColor (Color.White); Setontouchlistener (NewOntouchlistener () {@Override Public BooleanOnTouch (View V, motionevent event) { point point=NewPoint (int) Event.getx (), (int) event.gety ()); if(event.getaction () = =Motionevent.action_down) {allpoints=NewArraylist<point>(); Allpoints.add (point); } Else if(event.getaction () = =motionevent.action_up) {Allpoints.add (point); } Else if(event.getaction () = =motionevent.action_move) {Allpoints.add (point); Mypaintview. This. Postinvalidate (); } return true; } }); } @Overrideprotected voidOnDraw (canvas canvas) {Super. OnDraw (canvas); Paint Paint=NewPaint (); Paint.setcolor (color.red); if(Allpoints.size () >1) {Iterator<Point> iterator=Allpoints.iterator (); Point Firstpoint=NULL; Point Lastpoint=NULL; while(Iterator.hasnext ()) {if(firstpoint==NULL) {Firstpoint=Iterator.next (); } Else{ if(lastpoint!=NULL) {Firstpoint=Lastpoint; } lastpoint=Iterator.next (); Canvas.drawline (Firstpoint.x,firstpoint.y,lastpoint.x,lastpoint.y,paint); } } } }}
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout 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 " android:orientation=" vertical " tools:context= "Com.pingyijinren.helloworld.MainActivity" > < Com.pingyijinren.helloworld.MyPaintView android:layout_width= "Match_parent" android: Layout_height= "Match_parent"/></linearlayout>
Package Com.pingyijinren.helloworld; Import android.support.v7.app.AppCompatActivity; Import Android.os.Bundle; Public class extends appcompatactivity { @Override protectedvoid onCreate (Bundle Savedinstancestate) { super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); }}
Implementing a drawing board