Android Surfaceview and view draw a touch trajectory _android

Source: Internet
Author: User
Tags abs gety stub

First, Introduction
         want to implement a blank artboard, which can draw the trajectory of the slide, so a small demand. Generally speaking, there are two ways to implement, view or Surfaceview. Let's look at two ways to achieve this.
Two, implementing the principle
         First, a simple implementation principle:
        (1) Use a white bitmap as the artboard
       (2) Draw lines with canvas on bitmap
       (3) to draw a smooth curve, use the canvas DrawPath (path,paint) method.
       (4) Simultaneous use of Bezier curves for smoother curves
Three, view implementation
directly paste code:

Package Picturegame.view; 
Import Android.annotation.SuppressLint; 
Import Android.content.Context; 
Import Android.graphics.Bitmap; 
Import Android.graphics.BitmapFactory; 
Import Android.graphics.Canvas; 
Import Android.graphics.Color; 
Import Android.graphics.Paint; 
Import Android.graphics.Paint.Style; 
Import Android.graphics.Path; 
Import Android.util.AttributeSet; 
Import android.view.MotionEvent; 
 
Import Android.view.View; 
 
Import COM.WINTON.PICTUREGAME.R; /** * @ClassName: Gameview * @Description: TODO (Describe the role of this class in one sentence) * @author Winton winton_by@126.com * @date September 26, 2015 Morning 8:54:37 * */public class Gameview extends view{private Paint = null;//Private Paint Bitmap 
  
 AP = null;//Original Figure private Bitmap new1bitmap = null; 
  
 Private Bitmap new2bitmap = null; 
  
 private float Clickx = 0; 
  
 private float clicky=0; 
  
 private float startx=0; 
  
 private float starty=0; 
  
 Private Boolean ismove = true; Private Boolean isclear = fAlse; 
  
  
 
 private int color =color.red;//default brush color private float strokewidth =20f;//default brush width Path mpath; 
  Public Gameview {This (context,null); TODO auto-generated Constructor stub} public Gameview (context Context,attributeset Atts) {This (context,atts,0) 
  ; TODO auto-generated Constructor stub} @SuppressWarnings ("Static-access") public Gameview (Context Context,attribu 
  Teset Atts,int Defstyle) {super (Context,atts,defstyle); TODO auto-generated constructor stub originalbitmap = Bitmapfactory.decoderesource (Getresources (), R.drawable.de 
  fault_pic). Copy (Bitmap.Config.ARGB_8888, true);//White artboard new1bitmap=originalbitmap.createbitmap (ORIGINALBITMAP); 
 Mpath=new Path (); 
  //Clearly @SuppressWarnings ("static-access") public void Clear () {isclear =true; 
  New2bitmap=originalbitmap.createbitmap (ORIGINALBITMAP); 
Invalidate ()//reset} public void Setstrokewidth (float width) {this.strokewidth=width;  Initpaint (); 
  @Override protected void OnDraw (Canvas Canvas) {//TODO auto-generated Method Stub Super.ondraw (Canvas); 
   
 Canvas.drawbitmap (writer (new1bitmap), 0,0, NULL); @SuppressLint ("clickableviewaccessibility") @Override public boolean ontouchevent (Motionevent event) {//To 
   
  Do auto-generated method stub Clickx =event.getx (); 
   
  Clicky=event.gety (); 
   if (Event.getaction () ==motionevent.action_down) {//hand pointing down the screen triggers the Startx=clickx; 
   Starty=clicky; 
   Mpath.reset (); 
    
Mpath.moveto (Clickx, clicky); 
Ismove =false; 
Invalidate (); 
  return true; 
   else if (event.getaction () ==motionevent.action_move) {//the finger moves when the float dx=math.abs (CLICKX-STARTX) is triggered; 
Float Dy=math.abs (clicky-starty); if (dx>=3| | 
    dy>=3) {//Set the operation point of the Bezier curve as the beginning and end point of the half float CX = (Clickx + startx)/2; 
    float CY = (clicky + starty)/2; 
     
    Mpath.quadto (Startx,starty, CX, CY); 
    Startx=clickx; StArty=clicky; 
}//Ismove =true; 
Invalidate (); 
  return true; 
  } invalidate (); 
 return true; /** * @Title: Writer * @Description: TODO (Describe the effect of this method in one sentence) * @param @param pic * @param @return Settings file * 
   
  @return Bitmap return type * @throws/public Bitmap writer (Bitmap pic) {initpaint (); 
  Canvas Canvas =null; 
  if (isclear) {canvas=new canvas (new2bitmap); 
  }else{canvas=new canvas (pic); 
  //canvas.drawline (StartX, Starty, Clickx, clicky, paint);//Draw Line Canvas.drawpath (MPath, paint); 
  if (isclear) {return new2bitmap; 
 } return pic; private void Initpaint () {paint = new paint ();//Initialize Brush Paint.setstyle (style.stroke);//set to draw line Pai 
 Nt.setantialias (TRUE);/Set brush anti-aliasing paint.setcolor (color);/Set Brush color paint.setstrokewidth (strokewidth);/Set Brush width /** * @Title: SetColor * @Description: TODO (set brush color) * @param @param color Set file * @return void return type * @ THrows */public void setcolor (int color) {this.color=color; 
 Initpaint (); 
 Public Bitmap Getpaint () {return new1bitmap; 
 } 
}

Look at the effect:

Basically meet the demand
Third, Surfaceview implementation

Package Picturegame.view; 
Import Android.content.Context; 
Import Android.graphics.Bitmap; 
Import Android.graphics.BitmapFactory; 
Import Android.graphics.Canvas; 
Import Android.graphics.Paint; 
Import Android.graphics.Paint.Style; 
Import Android.graphics.Path; 
Import Android.util.AttributeSet; 
Import android.view.MotionEvent; 
Import Android.view.SurfaceHolder; 
Import Android.view.SurfaceHolder.Callback; 
 
Import Android.view.SurfaceView; 
 
Import COM.WINTON.PICTUREGAME.R;  public class Gameviewsurface extends Surfaceview implements callback,runnable{/** control game update Cycle **/Boolean mrunning 
  
 = false; 
  
 /** Control Game Loop **/Boolean misrunning = false; 
 
 /** every 50 frames refresh screen **/public static final int time_in_frame = 50; private int paintcolor=android.graphics.color.white;//Default brush color is black private float paintwidth=2f;//default brush width private sty  Le paintstyle=style.stroke;//default brush style private int paintalph=255;//default opaque private path mpath;//path private Paint mpaint;//paintingPen private float startx=0.0f;//initial x private float starty=0.0f;//initial y private surfaceholder surfaceholder; 
  
 Public Canvas Mcanvas; 
  
 public Boolean first=true; 
  
 Bitmap BG; 
 Public Gameviewsurface {This (context,null); 
 Public Gameviewsurface (Context Context,attributeset attrs) {this (context,attrs,0); 
  Public Gameviewsurface (context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle); 
  TODO auto-generated Constructor stub this.setfocusable (true);/Set the current view has a touch event surfaceholder=getholder (); 
   
  Surfaceholder.addcallback (this); 
  Mpath=new Path (); 
   
  Initpaint (); BG = Bitmapfactory.decoderesource (Getresources (), r.drawable.default_pic). Copy (Bitmap.Config.ARGB_8888, true);// White artboard}/** * @Title: Initpaint * @Description: TODO (initialization brush) * @param set file * @return void return type * @throws * 
  /private void Initpaint () {mpaint=new Paint (); Mpaint.setantialias (TRUE);/antialiasing 
  Mpaint.setcolor (Paintcolor);//Brush Color Mpaint.setalpha (PAINTALPH);//Brush Transparency Mpaint.setstyle (Paintstyle);//Set Brush style MP 
  Aint.setstrokewidth (paintwidth);//Set brush width} public void Dodraw () {Mcanvas=surfaceholder.lockcanvas (); 
 Mcanvas.drawpath (MPath, mpaint);//Draw Surfaceholder.unlockcanvasandpost (Mcanvas); @Override public boolean ontouchevent (Motionevent event) {//TODO auto-generated Method stub switch (eve 
   Nt.getaction ()) {case Motionevent.action_down://hand touch screen triggers Dotouchdown (event); 
  Break 
   Case Motionevent.action_move://Hand sliding trigger dotouchmove (event); 
    
  Break 
    
 
  Case MOTIONEVENT.ACTION_UP://Trigger break when lifting hand; 
  Default:break; 
 return true; /** * @Title: Dotouchdown * @Description: TODO (what needs to be done when touching the screen) * @param @param event settings file * @return void return class 
  Type * @throws/private void Dotouchdown (Motionevent event) {float touchx=event.getx (); 
  float touchy=event.gety (); STartx=touchx; 
  Starty=touchy; 
  Mpath.reset (); 
 Mpath.moveto (Touchx, touchy); /** * @Title: Dotouchmove * @Description: TODO (What to do when the hand slides on the screen) * @param @param event settings file * @return void return class 
  Type * @throws/private void Dotouchmove (Motionevent event) {float touchx=event.getx (); 
   
  float touchy=event.gety (); Float Dx=math.abs (TOUCHX-STARTX)//moving distance float dy =math.abs (TOUCHY-STARTX);//moving distance if (dx>3| | 
   dy>3) {float cx= (TOUCHX+STARTX)/2; 
   Float cy= (touchy+starty)/2; 
    
   Mpath.quadto (StartX, Starty, CX, CY); 
   Startx=touchx; 
    
  Starty=touchy; 
  } public void Setpaintcolor (int paintcolor) {this.paintcolor = Paintcolor; 
 Initpaint (); 
  public void Setpaintwidth (float paintwidth) {this.paintwidth = Paintwidth; 
 Initpaint (); 
  The public void Setpaintstyle (Style paintstyle) {this.paintstyle = Paintstyle; 
 Initpaint (); } public void Setpaintalph (int paintalph) {This.paintalph = PAIntalph; 
 Initpaint (); @Override public void Run () {//TODO auto-generated method stub while (misrunning) {/** to get update tour 
   The time before the play **/long starttime = System.currenttimemillis (); 
   /** here plus the line Cheng Ann full lock **/synchronized (surfaceholder) {Dodraw (); 
  
   /** get update game end time **/long endtime = System.currenttimemillis (); 
  
   /** calculates the number of milliseconds the game updates **/int difftime = (int) (endtime-starttime); /** ensure that each update time is 50 frames **/while (difftime <= time_in_frame) {difftime = (int) (System.currenttimemillis ()-Startt 
    IME); 
   /** thread waits for **/Thread.yield (); 
  @Override public void surfacecreated (Surfaceholder holder) {//TODO auto-generated a stub 
  Mcanvas =surfaceholder.lockcanvas (); 
  Mcanvas.drawbitmap (BG, 0,0, NULL); 
   
  Surfaceholder.unlockcanvasandpost (Mcanvas); 
  Misrunning=true; 
 New Thread (This). Start (); @Override public void surfacechanged (surfaceholder holder, int format, intwidth, int height) {//TODO auto-generated method stub} @Override public void surfacedestroyed (SURFACEH 
 Older holder) {//TODO auto-generated method Stub misrunning = false; 
 } 
  
  
}

See how it works:

When I do not set the background is no problem, but the use of the background will not stop flashing, do not know that there are no students know, you can say.

You can read this article "solve the Android Surfaceview drawing touch Path Flicker Problem method", perhaps to help everyone's learning.

V. Summary
all two ways are achievable, and careful comparison finds that the Surfaceview response is much faster than view, and the view must be easier to implement with Surfaceview.
View is used to display a passive update of an animation that requires an action to be updated, while Surfaceview is used for active update animations, such as displaying a running puppy on the interface.
The view update interface is in the UI main thread. Surfaceview is to start a thread update interface.

The above is the entire content of this article, I hope you like.

Related Article

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.