Imitation Baidu red Envelope Fu Bag Interface Instance code _java

Source: Internet
Author: User
Tags addchild gety

The new year to the new year, red envelopes non-stop. When I snatched a red envelope, I accidentally found Baidu's Fu bag interface is very good, so take time to write a special article to complete the Baidu Red Envelopes interface bar.

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. 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). 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 < Getchildcount (); i++) {//The first few lines int rowspan = I/3;//column int column = i% 3; Android.view.View v = getchildat (i); v.layout (column * CHILDW Idth + childwidth/basenum, rowspan * childwidth + childwidth/basenum, column * childwidth + childwidth-childwidth/
Basenum, rowspan * childwidth + childwidth-childwidth/basenum); } @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasurespec, H
EIGHTMEASURESPEC); Traversal sets the size for each child View for (int i = 0; i < Getchildcount (); i++) {View v = getchildat (i); V.measure (Widthmeasurespec, Heigh
TMEASURESPEC); } 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 (GetContext (), 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 of the coordinate private to the
lower-right corner coordinate
private int 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;
}
public void setpointstate (int pointstate) {
this.pointstate = pointstate;
}
Public Point Getpointlefttop () {return
pointlefttop;
}
Public Point Getpointrightbottom () {return
pointrightbottom;
}
Public 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 class is simpler on 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
private 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 Pa
int 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 = Animationcallback;} public LYJGestureView (context
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.action_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 and return true if the end point and the starting point are not the picture;} else {//on behalf of the user's finger moved to the point I F (currentpoint = = null) {//First determine if the current point is null//If NULL, then assign the finger to currentpoint currentpoint = Pointat;
T this point to set 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 (POINTAT) | | Constants.point_state_selecTED = = Pointat.getpointstate ()) {canvas.drawcircle (Currentpoint.getcenterx (), Currentpoint.getcentery (), 20,
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 two points connected straight line, and save draw circle and line, and call the Zoom animation canvas.drawcircle (Pointat.getcenterx (), Pointat.getcentery (), 20,
Circlepaint);
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 the extra line new Handler (). postdelayed (New Clearlinerunnable (), 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 place where the user is currently moving between the point and point * * Private LY Jgesturepoint getpointat (int x, int y) {for (Lyjgesturepoint point:list) {//First determine if the point is int in the X coordinate of the picture LEFTX = Point.getpoint
Lefttop (). x;
int rightx = Point.getpointrightbottom (). x; if (!) ( X >= leftx && x < RIGHTX) {///If False, skip to next comparison continue;//in the y-coordinate of the picture in the judgment point is int topy = Point.getpointlefttop (
). Y;
int bottomy = Point.getpointrightbottom (). Y; if (!) ( Y >= topy && y < bottomy) {///If False, skip to next comparison continue;//If this is done, then the position of the currently clicked Point is in the location of the points where it is being traversed.
return point;
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.first.getCenterY (), Pair.second.getCenterX (), Pair.second.getCenterY (), paint);//Draw line} for (Lyjcirclepoint lyjcirclepoint:circlepoints) {canvas.drawcircle (Lyjcirclepoint.getroundx (), Lyjcirclepoint.getroundy (),
Lyjcirclepoint.getradiu (), circlepaint); }//Draw canvas created with bitmap @Override protected void OnDraw (Canvas Canvas) {canvas.drawbitmap (bitmap, 0, 0, null);}

So you can get the following interface effect (of course, the reverse compiler Baidu Wallet, and no Baidu wallet in the picture, had to casually find a picture):

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.