Teach you to quickly implement the Android dynamic blur effect _android

Source: Internet
Author: User
Tags change settings

Objective

Yahoo weather interface on the slide when the background image will follow the move, the most important thing is that the background image will be based on the distance between the movement of the fingers to varying degrees of ambiguity, feeling very surprised, after all, as we all know, on the Android platform for fuzzy rendering is a fairly CPU-consuming and time-consuming operation, once the processing is not good , the cotton is unavoidable.

In general, given the efficiency, the best way to render a picture is to use it, OpenGL followed by using C++/C, which is the slowest to use Java code. But after Android came RenderScript out, we had a new choice, and the tests showed that the RenderScript rendering efficiency was comparable to using C + +, but RenderScript it was JNI much simpler to use than the use! At the same time, the Android team has provided a RenderScript support library that makes it available on a lower version of the Android platform.

However, RenderScript before using, for fuzzy a picture, it should be noted that we should try not to use the original size resolution of the picture, it is best to reduce the proportion of the picture, this small rendering efficiency is higher.

Implementation of dynamic Blur

How to use RenderScript to blur a picture? Don't say much nonsense, first on the core code:

public class Blurbitmap {/** * Picture scaling * * Private static final float Bitmap_scale = 0.4f;
 
 /** * Maximum ambiguity (between 0.0 and 25.0)/private static final float Blur_radius = 25f;  /** * Fuzzy picture of the specific method * * @param context Object * @param image needs to blur the picture * @return obfuscated picture * * public static Bitmap
  Blur (context, Bitmap image) {//calculate the long width int width = math.round (image.getwidth () * Bitmap_scale) after the picture is reduced;
 
  int height = Math.Round (image.getheight () * Bitmap_scale);
  Make the scaled picture a pre-rendered picture.
  Bitmap Inputbitmap = Bitmap.createscaledbitmap (image, width, height, false);
  Create a rendered picture of the output.
 
  Bitmap Outputbitmap = Bitmap.createbitmap (Inputbitmap);
  Create Renderscript Kernel object Renderscript rs = renderscript.create (context);
 
  Create a fuzzy effect of the Renderscript tool object Scriptintrinsicblur Blurscript = Scriptintrinsicblur.create (RS, Element.u8_4 (RS));
  Because Renderscript does not use a VM to allocate memory, you need to use the allocation class to create and allocate memory space.
  When you create a allocation object, the memory is empty, and you need to use CopyTo () to populate the data. Allocation Tmpin = Allocation.creaTefrombitmap (RS, inputbitmap);
 
  Allocation Tmpout = Allocation.createfrombitmap (RS, outputbitmap);
  Setting the blur degree of the rendering, 25f is the maximum ambiguity Blurscript.setradius (Blur_radius);
  Sets the input memory Blurscript.setinput (Tmpin) of the Blurscript object;
 
  Saves the output data to the output memory Blurscript.foreach (tmpout);
 
  Fill the data into the allocation Tmpout.copyto (OUTPUTBITMAP);
 return outputbitmap; }
}

After completing the above code, you need to add the following support to the app's Gradle file:

 Defaultconfig {
 ...
 .. Renderscripttargetapi
 renderscriptsupportmodeenabled True
}

The code makes a simple comment to help understand, and if you need more information, you can check the official documentation

Then we can look at the blur before and after the effect of comparison:

After blurring the picture, the next thing to consider is how to implement dynamic blur, and one thing to note is that even though we use RenderScript this efficient rendering method, in the actual test, rendering a 500*700 resolution PNG format picture, on my pro 6 phone, Still need about 50ms of time, obviously if using the above code for real-time rendering, will cause a serious interface of the cotton.

Now that this road is not going to go through in real time, then we need to do something different, I can provide a way here: first the picture to the maximum degree of fuzzy processing, and then placed the original image on the blurred picture above, by constantly changing the original transparency (alpha value) to achieve dynamic blur effect.

The simple code is as follows:

public class Mainactivity extends Appcompatactivity {/** * Original picture control * * Private ImageView moriginimg;
 
 /** * Fuzzy picture control/private ImageView mbluredimage;
 
 /** * progress bar SeekBar * * Private SeekBar Mseekbar;
 
 /** * Display the progress of the text * * Private TextView MPROGRESSTV;
 
 /** * Transparency * * private int malpha;
 
 /** * Original picture * * Private Bitmap Mtempbitmap;
 
 /** * Blurred picture * * * private Bitmap Mfinalbitmap;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 
  Setcontentview (R.layout.activity_main);
 
  Initialize view initviews ();
  Get Picture Mtempbitmap = Bitmapfactory.decoderesource (Getresources (), R.drawable.dayu);
 
  Mfinalbitmap = Blurbitmap.blur (this, mtempbitmap);
  Fill the blurred image and original mbluredimage.setimagebitmap (MFINALBITMAP);
 
  Moriginimg.setimagebitmap (MTEMPBITMAP);
 Handle Seekbar Sliding event setseekbar (); }/** * Initialization view/private void Initviews () {mbluredimage = (ImageView) Findviewbyid (R.id.activity_main_blurED_IMG);
  Moriginimg = (ImageView) Findviewbyid (r.id.activity_main_origin_img);
  Mseekbar = (SeekBar) Findviewbyid (R.id.activity_main_seekbar);
 Mprogresstv = (TextView) Findviewbyid (R.ID.ACTIVITY_MAIN_PROGRESS_TV);
  /** * Handle Seekbar sliding event/private void Setseekbar () {Mseekbar.setmax (100); Mseekbar.setonseekbarchangelistener (New Seekbar.onseekbarchangelistener () {@Override public void onprogresschanged (
    SeekBar SeekBar, int progress, Boolean fromuser) {malpha = progress;
    Moriginimg.setalpha ((int) (255-malpha * 2.55));
   Mprogresstv.settext (string.valueof (Malpha)); @Override public void Onstarttrackingtouch (SeekBar SeekBar) {} @Override public void Onstoptrackin
 Gtouch (SeekBar SeekBar) {}}); }
}

The

XML layout file code is as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/"
 Android "android:orientation=" vertical "android:id=" @+id/activity_main "android:layout_width=" Match_parent " android:layout_height= "Match_parent" > <framelayout android:layout_width= "match_parent" Android:layout_ weight= "1" android:layout_height= "0DP" > <imageview android:id= "@+id/activity_main_blured_img" ANDROID:SC Aletype= "Centercrop" android:src= "@drawable/dayu" android:layout_width= "match_parent" android:layout_height= "MATC H_parent "/> <imageview android:id= @+id/activity_main_origin_img" android:scaletype= "CenterCrop" Androi D:layout_width= "Match_parent" android:layout_height= "match_parent"/> </FrameLayout> <linearlayout and roid:orientation= "vertical" android:layout_width= "match_parent" android:layout_height= "80DP" > <seekbar an droid:layout_margintop= "@dimen/activity_vertical_Margin "android:id=" @+id/activity_main_seekbar "android:layout_width=" match_parent "android:layout_height=" Wrap_c Ontent "android:layout_marginleft=" 16DP "android:layout_marginright=" 16DP "/> <textview android:id=" @+id /activity_main_progress_tv "android:text=" 0 "android:textsize=" 24sp "android:layout_gravity=" center "android:l Ayout_width= "Wrap_content" android:layout_height= "wrap_content"/> </LinearLayout> </LinearLayout>

The effect is as follows:

What do you think? Is it a simple look? Only need to call the fuzzy processing method, and in the Seekbar sliding monitor inside calls the original image setAlpha() method, realizes the dynamic blur effect.

You think this is over? No, no, our purpose is not so simple, oh, no, it's not so easy. Do you remember when you said it at the beginning of the article? Our ultimate goal is to simply imitate the interface effect of Yahoo weather.

Imitation Yahoo Weather interface

With the above foundation, you can easily imitate the interface effect of Yahoo weather. To put it simply, on the basis of the effect of the above system, there are two points to be noted here:

You need to listen for a slide event and then call the background picture to setTop() move the picture up a distance.
To pan up the picture, you also need to manually increase the height of the picture, otherwise the picture is translated upward, the bottom will be white. The core code to set the height of the picture is as follows:

WindowManager wm = (WindowManager) context.getsystemservice (context.window_service);
Display display = Wm.getdefaultdisplay ();
Point point = new Point ();
Display.getsize (point);
Gets the height int height
= point.y to the ImageView;
Viewgroup.layoutparams params = Imageview.getlayoutparams ();
Params.width = ViewGroup.LayoutParams.MATCH_PARENT;
The height of the ImageView is increased by
params.height = height +;
Apply change settings
imageview.requestlayout ();

Complete the above two points of content, basic can imitate the Yahoo weather home.

Combined with the first example of the demo, the effect is as follows:

Summarize

The above is the entire content of this article, the effect is not very good after realization? Interested friends quickly do-it-yourself, I hope this article for everyone to develop Android can help.

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.