Android imitation Baidu Fu bag Red Envelope interface _android

Source: Internet
Author: User
Tags addchild gety

Immediately to the double 11, red envelopes, Time is ample, Rob red envelopes when the accident found Baidu's Fu bag interface is also good, think about a special blog to complete its interface.

Of course, this is actually the evolutionary version of unlocking the interface. However, it contains a lot of knowledge, write a blog log to see what the specific technical points. See

Look at Baidu's effect chart:

1. Programming Ideas

Look at the interface, it is not difficult to find, it is a container to put nine of pictures, drawing in fact, you can create a separate transparent view is responsible for drawing lines and circles. Below we will introduce the implementation process.

㈠ Custom ViewGroup

We know that a custom viewgroup must implement its OnLayout () method. This method is called when the child view location and size are set. There is also a onmeasure () method that measures the view and its contents to determine the width and height of the view.

㈡ stores the position and drawing parameters of its point and circle

When you return to the interface, the contents of the previous drawing interface are not saved, and must be stored for redrawing when drawing to the interface

㈢ Simple Zoom Animation

㈣ Custom View Implementation Drawing interface

㈤ when drawing completes, clears the interface to draw the content, and guarantees not to connect the duplicate picture

We will complete these steps below.

2. Custom ViewGroup

The starting task is to distribute nine images evenly across the picture, displayed in the mobile interface. The code is as follows:

public class Lyjviewgroup extends ViewGroup implements lyjgesturedrawline.onanimationcallback{/** * Width of each point area * *
  private int childwidth;
  /*** * contexts/private context;
  /*** * Save Picture Point position * * Private list<lyjgesturepoint> List;
   /*** * CREATE view to make it above viewgroup.
  * * Private Lyjgestureview gesturedrawline;
  private int basenum = 5;
    Public Lyjviewgroup {Super (context);
    This.context = context;
    This.list = new arraylist<> ();
    Displaymetrics metric = new Displaymetrics ();
    (activity). Getwindowmanager (). Getdefaultdisplay (). Getmetrics (Metric);   Childwidth = METRIC.WIDTHPIXELS/3;
    Screen width (pixel) addChild ();
    Initializes a view Gesturedrawline = new Lyjgestureview (context, list) that can be drawn to the line;
  Gesturedrawline.setanimationcallback (this);
    The public void Setparentview (viewgroup parent) {//Gets the width of the screen displaymetrics metric = new Displaymetrics (); (activity) the context). Getwindowmanager (). gEtdefaultdisplay (). Getmetrics (Metric);
    int width = metric.widthpixels;
    Layoutparams layoutparams = new Layoutparams (width, width);
    This.setlayoutparams (Layoutparams);
    Gesturedrawline.setlayoutparams (Layoutparams);
    Parent.addview (this);
  Parent.addview (Gesturedrawline); @Override protected void OnLayout (Boolean changed, int l, int t, int r, int b) {for (int i = 0; i < Getchild Count ();
      i++) {//The first few lines int rowspan = I/3;
      Number of columns int column = i% 3;
      Android.view.View v = getchildat (i); V.layout (column * childwidth + childwidth/basenum, rowspan * childwidth + childwidth/basenum, column * child
    Width + childwidth-childwidth/basenum, rowspan * childwidth + childwidth-childwidth/basenum); } @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasu
    Respec, Heightmeasurespec); Traversal sets the size of each child view for (int i = 0; i < Getchildcount ();
      i++) {View v = getchildat (i);
    V.measure (Widthmeasurespec, Heightmeasurespec);
      } private void AddChild () {for (int i = 0; i < 9; i++) {ImageView image = new ImageView (context);
      Image.setbackgroundresource (R.drawable.marker);
      This.addview (image);
      Invalidate ();
      The first few lines of int rowspan = I/3;
      Number of columns int column = i% 3;
      Defines the upper-left corner of the point and the lower-right corner of the coordinate int leftx = column * childwidth + childwidth/basenum;
      int topy = rowspan * childwidth + childwidth/basenum;
      int rightx = column * childwidth + childwidth-childwidth/basenum;
      int bottomy = rowspan * childwidth + childwidth-childwidth/basenum;
      Lyjgesturepoint p = new Lyjgesturepoint (LEFTX, Topy, rightx,bottomy,i);
    This.list.add (P); @Override public void startanimationimage (int i) {Animation animation= animationutils.loadanimation (getc
    Ontext (), R.anim.gridlayout_child_scale_anim); Getchildat (i) StartanImation (animation);



 }
}

3. Custom Point Class

As the name suggests, is to get the relevant properties of the point, where the underlying property picture in the upper-left corner coordinates and the lower right corner coordinates, calculate the center of the picture to get the picture center point. A status token that indicates whether the point is drawn to the picture. The following is actually the body class:

public class Lyjgesturepoint {private point pointlefttop;//the upper-left corner coordinates private-point pointrightbottom;//the lower-right corner coordinate private in

  T centerx;//Picture Center point x Coordinate private int centery;//Picture center point y coordinate private int pointstate;//Whether click on the picture private int num;
  public int Getnum () {return num;
  public int getpointstate () {return pointstate;
  The public void setpointstate (int pointstate) {this.pointstate = pointstate;
  Public Point Getpointlefttop () {return pointlefttop;
  Public Point Getpointrightbottom () {return pointrightbottom;
    Lyjgesturepoint (int left,int top,int right,int bottom,int i) {this.pointlefttop=new point (left,top);
    This.pointrightbottom=new Point (Right,bottom);
  This.num=i;
    public int Getcenterx () {this.centerx= (this.pointlefttop.x+this.pointrightbottom.x)/2;
  return CenterX;
    public int getcentery () {this.centery= (THIS.POINTLEFTTOP.Y+THIS.POINTRIGHTBOTTOM.Y)/2;
  return centery; } 4. Custom circle class This kind of simplificationOnly three attributes (Circle center point coordinates and RADIUS), the code is as follows: public class Lyjcirclepoint {private int roundx;//Circle Center point x Coordinate private int roundy;//Circle Center point Y coordinate p
  rivate int radiu;//Circle radius public int Getradiu () {return radiu;
  public int getroundx () {return roundx;
  public int Getroundy () {return roundy;
    Public lyjcirclepoint (int roundx,int roundy,int radiu) {this.roundx=roundx;
    This.roundy=roundy;
  This.radiu=radiu;

 }
}

5. Implementing custom Drawing Class View

The code is as follows:

public class Lyjgestureview extends Android.view.View {/*** * Declaration line Brush/private Paint Paint;
  /*** * Declaration Circle Brush/Private Paint circlepaint;
  /*** * Canvas/private Canvas Canvas;
  /*** * Bitmap/private Bitmap Bitmap;
  /*** * Equipped with each view coordinate set, used to determine whether the point in which/private list<lyjgesturepoint> List;
  /*** * Record Painted line * * Private list<pair<lyjgesturepoint, lyjgesturepoint>> linelist;
  /*** * Record The Painted circle * * Private list<lyjcirclepoint> circlepoints;
  /** * Finger is currently in which point inside/private lyjgesturepoint currentpoint;
  /*** * Finger Press the animation * * Private onanimationcallback animationcallback;
  public interface onanimationcallback{public void startanimationimage (int i); } public void Setanimationcallback (Onanimationcallback animationcallback) {this.animationcallback = AnimationCallb
  Ack
    Public Lyjgestureview (context, list<lyjgesturepoint> List) {super (context); LOG.I (GetClass () getnAme (), "gesturedrawline");
    Paint = new Paint (paint.dither_flag);//Create a Brush circlepaint=new paint (paint.dither_flag);
    Displaymetrics metric = new Displaymetrics ();
    (activity). Getwindowmanager (). Getdefaultdisplay (). Getmetrics (Metric);
    LOG.I (GetClass (). GetName (), "widthpixels" + metric.widthpixels);
    LOG.I (GetClass (). GetName (), "heightpixels" + metric.heightpixels); Bitmap = Bitmap.createbitmap (Metric.widthpixels, Metric.heightpixels, Bitmap.Config.ARGB_8888);
    Sets the bitmap's width high canvas = new canvas ();
    Canvas.setbitmap (bitmap); Paint.setstyle (Paint.Style.STROKE)//Set not filled paint.setstrokewidth (20);//pen width 20 pixel paint.setcolor (245, 142,
    33)//sets the default line color Paint.setantialias (TRUE);//does not show Sawtooth Circlepaint.setstyle (Paint.Style.FILL);
    Circlepaint.setstrokewidth (1);
    Circlepaint.setantialias (TRUE);

    Circlepaint.setcolor (Color.rgb (245, 142, 33));
    This.list = list;
    This.linelist = new arraylist<> (); This.circlepointS=new arraylist<> (); @Override public boolean ontouchevent (Motionevent event) {switch (event.getaction ()) {case MOTIONEVENT.A
        Ction_down://Determine which point the current click is within currentpoint = getpointat (int) event.getx (), (int) event.gety ());
          if (currentpoint!= null) {currentpoint.setpointstate (constants.point_state_selected);
          This.animationCallback.startAnimationImage (Currentpoint.getnum ());
          Canvas.drawcircle (Currentpoint.getcenterx (), Currentpoint.getcentery (), circlepaint);
        Circlepoints.add (New Lyjcirclepoint (Currentpoint.getcenterx (), Currentpoint.getcentery (), 20));
        } invalidate ();
      Break
        Case MotionEvent.ACTION_MOVE:clearScreenAndDrawList ();
        Gets where the current move position is in lyjgesturepoint Pointat = Getpointat ((int) event.getx (), (int) event.gety ());
  if (Currentpoint = = NULL && Pointat = null) {//You press the finger on the screen to slide, if the end point and the beginning are not the picture then return true;      else {///on behalf of the user's finger moved to the dot if (Currentpoint = null) {//first to determine if the current point is null//If empty, then move the finger to the dot assignment
            Value to currentpoint currentpoint = Pointat;
            Set the Currentpoint point to the selected state;
          Currentpoint.setpointstate (constants.point_state_selected); If the point you are moving to is not a picture area or moves to your own place, or if the picture is already selected, draw a straight line. if (Pointat = null | | currentpoint.equals (POI Ntat) | | constants.point_state_selected = = Pointat.getpointstate ()) {canvas.drawcircle () (Currentpoint.getcenterx), current
          Point.getcentery (), circlepaint);
          Circlepoints.add (New Lyjcirclepoint (Currentpoint.getcenterx (), Currentpoint.getcentery (), 20));
        Canvas.drawline (Currentpoint.getcenterx (), Currentpoint.getcentery (), Event.getx (), event.gety (), paint); }else{//other cases draw a two-point straight line and save the drawing circle and line and invoke the Zoom animation canvas.drawcircle (Pointat.getcenterx (), Pointat.getcentery (), 20,CIRC
          Lepaint); Circlepoints.add (New Lyjcirclepoint (Pointat).Getcenterx (), Pointat.getcentery (), 20));
          This.animationCallback.startAnimationImage (Pointat.getnum ());
          Pointat.setpointstate (constants.point_state_selected); Canvas.drawline (Currentpoint.getcenterx (), Currentpoint.getcentery (), Pointat.getcenterx (), PointAt.getCenterY (),
          Paint);
          Pair<lyjgesturepoint, lyjgesturepoint> Pair = new Pair<> (currentpoint, Pointat);
          Linelist.add (pair);
        currentpoint=pointat;//sets the selection point to the current point.
      Invalidate ()//Redraw break; Case MotionEvent.ACTION_UP:clearScreenAndDrawList ()//Prevent an extra line new Handler (). postdelayed (New Clearli
      Nerunnable (), 1000);//1 seconds to clear the drawing interface invalidate ()//Redraw break;
    Default:break;
  return true;
      Class Clearlinerunnable implements Runnable {public void run () {//Empty save point with round collection linelist.clear ();
      Circlepoints.clear ();
      Redraw interface Clearscreenanddrawlist (); For(Lyjgesturepoint p:list)
      {//Set it to initialize unchecked state p.setpointstate (constants.point_state_normal);
    } invalidate (); }/** * Through the location of the point to find the point is contained in which points inside the * * @param x * @param y * @return if not found, then return null, representing the current mobile location of the user Between the point and the point * * Private lyjgesturepoint Getpointat (int x, int y) {for (Lyjgesturepoint point:list) {//First, judge the point is
      no int leftx = Point.getpointlefttop () x in the X coordinate of the picture.
      int rightx = Point.getpointrightbottom (). x; if (!) (
      X >= leftx && x < RIGHTX) {///If False, skip to next comparison continue;
      ///At the judge Point whether the y-coordinate of the picture is int topy = Point.getpointlefttop (). Y;
      int bottomy = Point.getpointrightbottom (). Y; if (!) (
      Y >= topy && y < bottomy) {///If False, skip to next comparison continue;
    //If executed to this, then indicate the location of the current clicked Point in the position of the location where you are traversing the points.
  return null; /** * Clear all the lines on the screen, and then draw the line inside the collection * * private void Clearscreenanddrawlist () {Canvas. Drawcolor (Color.transparent, PorterDuff.Mode.CLEAR); For (Pair<lyjgesturepoint, lyjgesturepoint> pair:linelist) {canvas.drawline (Pair.first.getCenterX (), PAIR.F  Irst.getcentery (), Pair.second.getCenterX (), Pair.second.getCenterY (), paint);//Draw line} for (Lyjcirclepoint lyjcirclepoint:circlepoints) {canvas.drawcircle (Lyjcirclepoint.getroundx (), Lyjcirclepoint.getroundy (), lyjCircle
    Point.getradiu (), circlepaint); 
  }//Draw canvas created with bitmap @Override protected void OnDraw (Canvas Canvas) {canvas.drawbitmap (bitmap, 0, 0, NULL);

 }
}

Attached this article source code: Source Download

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.