Android fuzzy example-RenderScript-rendering and code

Source: Internet
Author: User


1. Program

Drag the red area to display the clear car section. Drag the slider below to change the Blur degree.

2. Program Implementation Method

The implementation idea is to use FrameLayout to create three layers. The bottom layer is a clear image, the middle layer is a blurred image, and the top layer is a red area, which is a clear picture.


Public static class PlaceholderFragment extends Fragment {// the new version of android adt-bundle includes a fragment in the activity by default. It is said that android stdio has long been like this: private ImageView mOriginIv; private ImageView javasuriv; private SeekBar mRadiusSb; public PlaceholderFragment () {}@ Overridepublic View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View rootView = inflater. infla Te (R. layout. fragment_main, container, false); return rootView;} @ Overridepublic void onActivityCreated (Bundle savedInstanceState) {super. onActivityCreated (savedInstanceState); mOriginIv = (ImageView) getActivity (). findViewById (R. id. origin_image); required uriv = (ImageView) getActivity (). findViewById (R. id. blur_image); mClearIv = (ImageView) getActivity (). findViewById (R. id. clear_image); mRadiusSb = (SeekBar) ge TActivity (). findViewById (R. id. radius_seekbar); drawBlurImage (); // initialize the fuzzy layer. SetSeekBarChangeListen (); // sets the SeekBar callback. When the slider position changes, the Blur layer is updated. // The delay is to ensure that the methods such as view. getX and view. getWidth can go to the numeric value. The delay is better for initialization. // If you want to read weidht and x for each visualization, you can call it in Activity # onWindowFocusChange. Runnable runnable = new Runnable () {@ Overridepublic void run () {OnMoveListener listener = new OnMoveListener () {@ Overridepublic void onMoved () {mOriginIv. buildDrawingCache (); clear (mOriginIv. getDrawingCache (), mClearIv, 10); // This is a good way to get the View to draw the image}; MoveUtils. enableMove (mClearIv, listener) ;}}; mClearIv. postDelayed (runnable, 500);} private void drawBlurImage () {mOriginIv. getViewTreeObserver (). addOnPreDraw Listener (new OnPreDrawListener () {@ Overridepublic boolean onPreDraw () {mOriginIv. getViewTreeObserver (). removeOnPreDrawListener (this); mOriginIv. buildDrawingCache (); float radius = mRadiusSb. getProgress (); if (radius <0.1) {// RenderScript requires that the radius must be between 0 and 25, and cannot be equal to radius = 0.1f;} if (radius> 24.9) {radius = 24.9f;} blur (mOriginIv. getDrawingCache (), radiuriv, radius); clear (mOriginIv. getDrawingCache (), mCle ArIv, 10); // In order to display the border, I am lazy and use 10px directly. Actually, it is 5dip. On the galaxy nexus of my mobile phone, 1dip = 2px, actually, it should be converted. Return true; // This is required by reference to the article. You have not tried false .}});} Private void setSeekBarChangeListen () {mRadiusSb. second (new second () {@ Overridepublic void second (SeekBar arg0) {}@ Overridepublic void onStartTrackingTouch (SeekBar arg0) {}@ Overridepublic void onProgressChanged (SeekBar arg0, int arg1, boolean arg2) {drawBlurImage () ;}}) ;}// generate a cropped image from bkg Based on The view Size. Then, based on the radius, blur the cropped image, and then set the blurred image to the view. @ TargetApi (Build. VERSION_CODES.JELLY_BEAN_MR1) private void blur (Bitmap bkg, View view, float radius) {// Bitmap overlay = Bitmap during image cropping. createBitmap (int) (view. getMeasuredWidth (), (int) (view. getMeasuredHeight (), Bitmap. config. ARGB_8888); Canvas canvas = new Canvas (overlay); canvas. translate (-view. getX (),-view. getY (); // set the coordinate system origin canvas. drawBitmap (bkg, 0, 0, null); // The image is drawn directly on the origin of the new coordinate system. If you set the coordinate system, it is equivalent to drawing an image on (view. getX (), view. getY). android uses the x-axis square to the right and the y-axis square to the downward direction. // RenderScript rs = RenderScript in the fuzzy image process. create (getActivity (); // RenderScript requires apilevel 17, which is disgusting. v8 support packages are not particularly useful. If you really want to blur them, let's do it with opencv jni. Allocation overlayAlloc = Allocation. createFromBitmap (rs, overlay); ScriptIntrinsicBlur blur = ScriptIntrinsicBlur. create (rs, overlayAlloc. getElement (); blur. setInput (overlayAlloc); blur. setRadius (radius); blur. forEach (overlayAlloc); overlayAlloc. copyTo (overlay); // sets the Image view. setBackground (new BitmapDrawable (getResources (), overlay); rs. destroy ();} // first, generate a cropped image from bkg Based on The view Size, and then set the cropped image to the view. Private void clear (Bitmap bkg, ImageView view, int paddingPx) {Bitmap overlay = Bitmap. createBitmap (int) (view. getMeasuredWidth ()-paddingPx * 2), (int) (view. getMeasuredHeight ()-paddingPx * 2), Bitmap. config. ARGB_8888); Canvas canvas = new Canvas (overlay); canvas. translate (-view. getX ()-paddingPx,-view. getY ()-paddingPx); canvas. drawBitmap (bkg, 0, 0, null); view. setImageDrawable (new BitmapDrawable (getResources (), overlay ));}}


3. Download Code 


The evil CSDN has uploaded the code, and it has not been reviewed for several hours... Note that the minsdk of the Code is relatively high. It is API Level17 and cannot be used. The RenderScript support library is not fixed.

4. Several Questions

RenderScriptAlthough there is support-v8 support library, but I will do, and did not compile successful. I also saw a Post saying that RenderScript has a problem on 2.3.5. Therefore, it is not very reliable. It is better to build jni + opencv by yourself. There are many fuzzy algorithms related to opencv on the Internet. In addition, if the image is large and fuzzy processing is time-consuming, it is best to perform it asynchronously.

Call time of getWidth, getHeight, and getLeftOnStart and onReusme cannot be used. They can only be used in onWindowFoucsChange. The example in this article is called during initialization, so the execution can be delayed for a while. If you need to call it every time you switch from the background to the foreground, you need to call it in onWindowFoucsChange.

Use canvas to crop bitmapPay attention to the coordinate system. android uses the x-axis square to the right.


private void clear(Bitmap bkg, ImageView view, int paddingPx) {Bitmap overlay = Bitmap.createBitmap((int) (view.getMeasuredWidth() - paddingPx * 2),(int) (view.getMeasuredHeight() - paddingPx * 2),Bitmap.Config.ARGB_8888);Canvas canvas = new Canvas(overlay);canvas.translate(-view.getX() - paddingPx, -view.getY() - paddingPx);canvas.drawBitmap(bkg, 0, 0, null);view.setImageDrawable(new BitmapDrawable(getResources(), overlay));}
Obtain Image Rendering Cache



mOriginIv.buildDrawingCache();clear(mOriginIv.getDrawingCache(), mClearIv, 10);
Allows the View to be dragged
A simple method is provided. The View can be dragged by Tag + onTouchEvent of the View.



package com.example.blurtest;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;public class MoveUtils {private static final int STATE_IDLE = 0;private static final int STATE_MOVING = 1;private static final int MIN_GAP = 5;private static class Info {public int state = STATE_IDLE;public float lastX = -1;public float lastY = -1;public OnMoveListener listener;}private static Info getInfo(View view) {if (view.getTag() == null) {view.setTag(new Info());}return (Info) (view.getTag());}private static void tryToMove(View view, MotionEvent ev) {Info info = getInfo(view);if (info.state != STATE_MOVING) {return;}float x = ev.getX() - info.lastX;float y = ev.getY() - info.lastY;if (Math.abs(x) < MIN_GAP && Math.abs(y) < MIN_GAP) {return;}view.setX(view.getX() + x);view.setY(view.getY() + y);view.invalidate();info.listener.onMoved();}public static void enableMove(View target, OnMoveListener listener) {Info info = new Info();info.listener = listener;target.setTag(info);target.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View view, MotionEvent ev) {Info info = getInfo(view);int action = ev.getAction() & MotionEvent.ACTION_MASK;switch (action) {case MotionEvent.ACTION_DOWN:info.state = STATE_MOVING;info.lastX = ev.getX();info.lastY = ev.getY();view.setTag(info);break;case MotionEvent.ACTION_MOVE:tryToMove(view, ev);break;case MotionEvent.ACTION_UP:info.state = STATE_IDLE;info.lastX = ev.getX();info.lastY = ev.getY();view.setTag(info);default:break;}return true;}});}public static interface OnMoveListener {public void onMoved();}}



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: 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.