Android realizes dynamic Gaussian blur effect _android

Source: Internet
Author: User

What is Gauss Blur?

Gaussian Blur (English: Gaussian Blur), also known as Gaussian smoothing, is widely used in image processing software such as Adobe Photoshop, GIMP, and Paint.NET, which is often used to reduce image noise and reduce the level of detail. The image produced by this fuzzy technique, whose visual effects are seen through a translucent screen, is markedly different from the effects of the lens defocus and the shadow of the general illumination.

What the? Can't you see? It doesn't matter, I can't see it, Wikipedia copied it back. Let's just put some pictures to see how this Gaussian blur is. Because Gaussian blur is most common in iOS, here are some pictures of the iOS NetEase cloud:

You can see the background of this interface, in fact, through the small picture in the middle of Figure 1, the advantage is that the integrity is very good, and not because of the image transition abrupt and affect the content of the interface reading.

So how do you achieve this on Android? It is recommended that the official offer of a tool in the support library be renderscript. There is more to this renderscript than this one, and some of the other features that can be read in the official document are not given here.

The reason for using this tool is actually very simple, that is, performance. Because of the drawing, if the performance is not good, then whether for high-quality graphics or change more requirements are difficult, and this tool will give full play to the device's computing power (CPU and GPU) to calculate, and is used in the C99 derivative language scripting, Compared to Java performance is greatly improved.

Speaking of this, some students started side, C99 derivative? What? This does not need to worry, for Gauss blur this implementation, Google official has given the corresponding solution, we do not need to write the corresponding script can be used, so don't worry.

We divide the whole problem into two parts:

① Gauss fuzzy realization;

② Dynamic Gaussian fuzzy implementation

① Gaussian fuzzy implementation

The first thing to say is that we're going to use the support Library, so the version is required:

Android SDK Tools version must be greater than or equal to 22.2

The Android SDK build-tools version must be greater than or equal to 18.1.0

If not, please upgrade with SDK Manager.

We then create our project and add the following code to the Build.gradle file for the corresponding module (the app that is created by default):

Defaultconfig {
    ...
    .. Renderscripttargetapi
    renderscriptsupportmodeenabled True
  }

Renderscripttargetapi: This is generally the same as the minimum version supported by the app.

Package Com.fndroid.renderscriptdemo;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.os.Bundle;
Import android.renderscript.Allocation;
Import android.renderscript.Element;
Import Android.renderscript.RenderScript;
Import Android.renderscript.ScriptIntrinsicBlur;
Import android.support.v7.app.AppCompatActivity;

Import Android.widget.ImageView;
  public class Mainactivity extends Appcompatactivity {private ImageView mimageview;
  Private Bitmap sampleimg;

  Private Bitmap gaussianblurimg;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Mimageview = (ImageView) Findviewbyid (R.ID.IV); sampleimg = Bitmapfactory.decoderesource (Getresources (), R.drawable.icon);
    Get the original gaussianblurimg = Blur (Sampleimg, 25f);
  Mimageview.setimagebitmap (GAUSSIANBLURIMG); Private Bitmap Blur (Bitmap bitmap,float radius) {Bitmap output = BitmAp.createbitmap (bitmap); Create output picture Renderscript rs = Renderscript.create (this); Construct a Renderscript object Scriptintrinsicblur Gaussianblue = Scriptintrinsicblur.create (RS, Element.u8_4 (RS)); Create a Gaussian blur script allocation Allin = Allocation.createfrombitmap (rs, bitmap); Create a script type for input allocation Allout = Allocation.createfrombitmap (rs, Output); Create a script type for output gaussianblue.setradius (RADIUS); Setting the fuzzy radius, the range 0f<radius<=25f gaussianblue.setinput (Allin); Sets the input script type Gaussianblue.foreach (allout); Executes the Gaussian blur algorithm and fills the result into the output script type Allout.copyto (output); Encode output memory as bitmap, picture size must pay attention to Rs.destroy ();
  Closes the Renderscript object, Api>=23 uses rs.releaseallcontexts () return output; }
}

Here the instructions are commented in the code. What you need to know is that the Renderscript has two versions, respectively:

Android.renderscript

Android.support.v8.renderscript

The code above uses the first one, and the second one is similar, and you can try it yourself.

Let's get down to the idea because renderscript is dependent on script , and as mentioned above,script is written by the C99 derivative language, and the code Scriptintrinsicblur is a script corresponding to the Gaussian fuzzy algorithm. The allocation object is a helper for converting objects in Java into the type required for script scripts, where two allocation objects are created to act as inputs and outputs, respectively. Then the Gaussian blur radius (RADIUS)is set. When ForEach is invoked, the script is executed, and the execution results are filled in the corresponding allocation of the output, and finally the CopyTo is converted to Bitmap Object returns.

Effect Chart:

② Dynamic Gaussian Blur

Most of the time, we may need a picture to show up at different levels of ambiguity. You may have noticed the blur radius of the above method, and we can do an experiment by dynamically changing this value through a seekbar to see the effect:

by moving the diagram can see , we drag SeekBar ,SeekBar has not been able to keep up with our drag. Why is that? The reason is that the rendering tool is superior in performance, but if the quality and size of the picture are high, it is often undesirable to modify the blur radius rendering directly.

The idea is to create a blurry picture to load in the ImageView , and then place a loaded original ImageViewon top of the ImageView , using Framelayout can let these two ImageView overlap again, and then when we need to dynamically change the degree of ambiguity, change the upper ImageView Bitmapalpha it's OK. Let's take a look at the effect chart first:

Using this method, the slide will be more smooth. (gif will be the normal speed after loading oh )

Here is a code reference bar:

public class Mainactivity extends Appcompatactivity implements Seekbar.onseekbarchangelistener {private ImageView Mima
  Geview;
  Private ImageView Mimageviewcover;
  Private Bitmap sampleimg;
  Private Bitmap gaussianblurimg;

  Private SeekBar Mseekbar;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Mimageview = (ImageView) Findviewbyid (R.ID.IV);
    Mseekbar = (SeekBar) Findviewbyid (R.ID.SB);
    Mimageviewcover = (ImageView) Findviewbyid (r.id.iv_cover); sampleimg = Bitmapfactory.decoderesource (Getresources (), R.drawable.icon);
    Get the original gaussianblurimg = Blur (Sampleimg, 25f);
    Mimageview.setimagebitmap (GAUSSIANBLURIMG);
  Mseekbar.setonseekbarchangelistener (this); Private Bitmap Blur (Bitmap Bitmap, float radius) {Bitmap output = Bitmap.createbitmap (Bitmap);//create export picture Ren Derscript rs = renderscript.create (this); Build a Renderscript object scriptintrInsicblur Gaussianblue = scriptintrinsicblur.create (RS, Element.u8_4 (RS)); Create a Gaussian blur script allocation Allin = Allocation.createfrombitmap (rs, bitmap); Open input memory allocation allout = Allocation.createfrombitmap (rs, Output); Open Output Memory Gaussianblue.setradius (RADIUS); Setting the fuzzy radius, the range 0f<radius<=25f gaussianblue.setinput (Allin); Set input memory Gaussianblue.foreach (allout); Fuzzy coding, and the memory is filled into the output memory allout.copyto (outputs); Encode output memory as bitmap, picture size must pay attention to Rs.destroy ();
  Closes the Renderscript object, Api>=23 uses rs.releaseallcontexts () return output; @Override public void onprogresschanged (SeekBar SeekBar, int progress, Boolean fromuser) {int alpha = 255-PR
    ogress;
  Mimageviewcover.setimagealpha (Alpha); @Override public void Onstarttrackingtouch (SeekBar SeekBar) {} @Override public void Onstoptrackingtouch (S Eekbar seekBar) {}}

Layout file:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/"
  Android "xmlns:app=" Http://schemas.android.com/apk/res-auto "xmlns:tools=" Http://schemas.android.com/tools " Android:id= "@+id/activity_main" android:layout_width= "match_parent" android:layout_height= "Match_parent" Android : orientation= "Vertical" tools:context= "com.fndroid.renderscriptdemo.MainActivity" > <framelayout android:lay Out_width= "Match_parent" android:layout_height= "0DP" android:layout_weight= "1" > <imageview androi D:id= "@+id/iv" android:layout_width= "match_parent" android:layout_height= "match_parent"/> <ImageVie
      W android:id= "@+id/iv_cover" android:layout_width= "match_parent" android:layout_height= "Match_parent" android:src= "@drawable/icon"/> </FrameLayout> <seekbar android:id= "@+id/sb" Android:layout_w Idth= "Match_parent" Android:layout_height= "wrap_content" android:max= "255"/> </LinearLayout> 

Summarize

The above is the realization of dynamic Gaussian blur in Android all the content, this article first introduced how to achieve Gaussian blur, and then introduce the implementation of dynamic effects, so that people more easily understand learning, I hope this article for everyone to develop Android help.

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.