Android view of the burst effect implementation method detailed _android

Source: Internet
Author: User
Tags explode sqlite database

The example of this article describes the implementation of the burst effect of view in Android. Share to everyone for your reference, specific as follows:

A few days ago Weibo was a very good Android open Source Component Brush Screen-Explosionfield, the effect is very cool, a bit like MIUI uninstall APP animation, first to feel.

Explosionfield not only the effect is very windy, the code is also very good to write, people can not help but to take a good read.

Create Explosionfield

Explosionfield inherits from View, draws an animation effect in the OnDraw method, and it provides a Attach2window method that can add Explosionfield one child View to the activity's root VI In EW.

public static Explosionfield Attach2window (activity activity) {
 ViewGroup Rootview = (viewgroup) Activity.findviewbyid (window.id_android_content);
 Explosionfield Explosionfield = new Explosionfield (activity);
 Rootview.addview (Explosionfield, New Viewgroup.layoutparams (
   ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
 return Explosionfield;
}

The Layoutparams property of the Explosionfield is set to Match_parent,
As a result, a view-exploding particle can be plotted in the region where the activity is located.

Knowledge Points: You can use window.id_android_content to replace ANDROID. R.id.content

The effect of shaking before the burst

In the View click event, after calling Mexplosionfield.explode (v), view first vibrates and then burst.

The vibration effect is relatively simple, set a [0, 1] interval valueanimator, then randomly translate the x and Y coordinates in the onanimationupdate of Animatorupdatelistener, and finally reduce the scale and alpha values dynamically to 0.

int startdelay = m;
Valueanimator animator = Valueanimator.offloat (0f, 1f). Setduration ();
Animator.addupdatelistener (New Valueanimator.animatorupdatelistener () {
 Random Random = new Random ();
 @Override public
 void Onanimationupdate (Valueanimator animation) {
  View.settranslationx (random.nextfloat ( )-0.5f) * View.getwidth () * 0.05f);
  View.settranslationy ((Random.nextfloat ()-0.5f) * view.getheight () * 0.05f);
 }
);
Animator.start ();
View.animate (). Setduration. Setstartdelay (Startdelay). ScaleX (0f). ScaleY (0f). Alpha (0f). Start ();

Create a bitmap from View

When the View was shaken, the most difficult burst was made, and the explosion was carried out at the same time as the hidden, to see the burst API first-

void Explode (Bitmap Bitmap, Rect bound, long startdelay, long duration)

The first two parameters bitmap and bound are key, and it is interesting to create the bitmap code through the View.

If the View is a imageview, and its drawable is a bitmapdrawable, you can get the Bitmap directly.

if (view instanceof ImageView) {
 drawable drawable = ((ImageView) view). Getdrawable ();
 if (drawable!= null && drawable instanceof bitmapdrawable) {return
  (bitmapdrawable) drawable). Getbitmap () ;
 }
}

If you are not a imageview, you can create a bitmap by following these steps:

1. Create a new Canvas

2. Create an empty bitmap based on the size of the View

3. Set the empty bitmap to the Canvas of the base cloth

4. Draw the view on the canvas

5. Set the canvas bitmap to NULL

Of course, you need to clear the view's focus before drawing, because the focus may change the UI state of a view.

The Scanvas used in the following code is a static variable, which saves the overhead of each creation.

View.clearfocus ();
Bitmap Bitmap = createbitmapsafely (View.getwidth (),
  view.getheight (), Bitmap.Config.ARGB_8888, 1);
if (bitmap!= null) {
 synchronized (Scanvas) {
  Canvas Canvas = Scanvas;
  Canvas.setbitmap (bitmap);
  View.draw (canvas);
  Canvas.setbitmap (null);
 }


The author creates bitmaps in a very ingenious way, and if you create a OOM when creating a new Bitmap, you can take the initiative to GC-SYSTEM.GC (), and then try creating again.

The way this function is implemented is to admire the author's skill.

public static Bitmap createbitmapsafely (int width, int height, bitmap.config Config, int retrycount) {
 try {
  ret Urn Bitmap.createbitmap (width, height, config);
 } catch (OutOfMemoryError e) {
  e.printstacktrace ();
  if (RetryCount > 0) {
   System.GC ();
   Return createbitmapsafely (width, height, config, retryCount-1);
  }
  return null;
 }
}

Out of the bitmap, there is also a very important parameter bound, it is relatively simple to create:

Rect r = new Rect ();
View.getglobalvisiblerect (r);
int[] location = new Int[2];
Getlocationonscreen (location);
R.offset (-location[0],-location[1]);
R.inset (-mexpandinset[0],-mexpandinset[1]);

First get the global visual area-Rect R of the view that needs to burst, and then Getlocationonscreen (location) to get the coordinates of the Explosionfield in the screen, and translate the visual area of the burst view according to the coordinates, so The burst effect is displayed in the Explosionfield and is then extended according to the Mexpandinset value (default 0).

What is the use of the bitmap and bound created? Let's go down and analyze.

Creating particles

Let's look at the whole picture of the method of exploding into particles:

public void explode (Bitmap Bitmap, Rect bound, long startdelay, long duration) {
 final explosionanimator explosion = n EW Explosionanimator (this, bitmap, bound);
 Explosion.addlistener (New Animatorlisteneradapter () {
  @Override public
  void Onanimationend (animator Animation) {
   mexplosions.remove (animation);
  }
 });
 Explosion.setstartdelay (startdelay);
 Explosion.setduration (duration);
 Mexplosions.add (explosion);
 Explosion.start ();
}

Here's an explanation of why a container-class variable-mexplosions is used to save a explosionanimator. Because the burst effect of multiple view in an activity may have to be done at the same time, keep each view corresponding to the burst animation to save, and so on the end of the animation and then delete.

The author defines a class that inherits from Valueanimator-Explosionanimator, which mainly does two things, one is to create the particle-the generateparticle, the other is to draw the particle-draw (Canvas Canvas).

Let's take a look at the constructor:

Public Explosionanimator (View container, Bitmap Bitmap, Rect bound) {
 mpaint = new Paint ();
 Mbound = new Rect (bound);
 int partlen =;
 Mparticles = new Particle[partlen * Partlen];
 Random Random = new Random (System.currenttimemillis ());
 int w = bitmap.getwidth ()/(Partlen + 2);
 int h = bitmap.getheight ()/(Partlen + 2);
 for (int i = 0; i < Partlen. i++) {for
  (int j = 0; J < Partlen; J +) {
   mparticles[(i * Partlen) + j] = Gen Erateparticle (Bitmap.getpixel (j + 1) * W, (i + 1) * h), random);
  }
 Mcontainer = container;
 Setfloatvalues (0f, end_value);
 Setinterpolator (default_interpolator);
 Setduration (default_duration);
}

According to the constructor, it is known that the author divides the bitmap into a matrix of x 17, with each element's width and height being W and h respectively.

int w = bitmap.getwidth ()/(Partlen + 2);
int h = bitmap.getheight ()/(Partlen + 2);

All particles are a matrix of x 15, which is the pixel value of the bitmap.

Bitmap.getpixel ((j + 1) * W, (i + 1) * h)

The structure is shown in the figure below, where the hollow part is the particle.

 
 000000000000000
 000000000000000
 000000000000
 000000000000000
 000000000000000
 0000000 00000000
 000000000000000
 000000000000000
 0000000000  00000
 000000000000000
 000000000000000
 0000000000000
 000000000000000
 000000000000000
 000000000000000 ●
 ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ●

Generateparticle will randomly generate a particle based on a certain algorithm. This part is more cumbersome, analysis omitted.

One of the more ingenious is its draw method:

public Boolean Draw (Canvas Canvas) {
 if (!isstarted ()) {return
  false;
 }
 for (particle particle:mparticles) {
  particle.advance ((float) getanimatedvalue ());
  if (Particle.alpha > 0f) {
   mpaint.setcolor (particle.color);
   Mpaint.setalpha ((int) (Color.alpha (particle.color) * particle.alpha));
   Canvas.drawcircle (particle.cx, particle.cy, Particle.radius, mpaint);
  }
 Mcontainer.invalidate ();
 return true;
}

At first I have been more puzzled, since the drawing of particles in the Explosionfield of the OnDraw method, it must be constantly refreshed, the results of the author is not to do so, the implementation of the method is truly stunning.

First, the author overloads the Start () method in the Explosionanimator class by invoking Mcontainer.invalidate (Mbound) to refresh the block corresponding to the View that will burst.

@Override public
void Start () {
 super.start ();
 Mcontainer.invalidate (Mbound);
}

While Mcontainer is the view-explosionfield of activity, its OnDraw method calls Explosionanimator draw method.

@Override
protected void OnDraw (Canvas Canvas) {
 super.ondraw (Canvas);
 for (Explosionanimator explosion:mexplosions) {
  explosion.draw (canvas);
 }
}

This creates a recursion that calls each other and refreshes until the alpha value of all the particles becomes 0, and the refresh stops.

public Boolean Draw (Canvas Canvas) {
 if (!isstarted ()) {return
  false;
 }
 for (particle particle:mparticles) {
  particle.advance ((float) getanimatedvalue ());
  if (Particle.alpha > 0f) {
   mpaint.setcolor (particle.color);
   Mpaint.setalpha ((int) (Color.alpha (particle.color) * particle.alpha));
   Canvas.drawcircle (particle.cx, particle.cy, Particle.radius, mpaint);
  }
 Mcontainer.invalidate ();
 return true;
}

Summarize

The code quality of this open source library is quite high and I admire the author.

More interested readers of Android-related content can view the site's topics: "The Overview of Android View View Tips", "Android operation XML Data Skills Summary", "Android programming activity Operation Skills Summary", " Android Resource Operation tips Summary, "Android file Operation Tips", "Android operation SQLite Database Skills Summary", "Android operation JSON format Data Skills summary", "Android Database Operating skills summary", " Android programming development of the SD card operation method Summary, "Android Development introduction and Advanced Course" and "Android Control usage Summary"

I hope this article will help you with the Android program.

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.