android programmatically blur imageview drawable

前端 未结 2 1479
感动是毒
感动是毒 2020-12-08 11:54

I want to programmatically blur and unblur images in Android.

I hear that android flag \"blur\" is no longer supported after API 14 , but I wanted to use Java method

2条回答
  •  长情又很酷
    2020-12-08 12:48

    For blurring an imageView or bitmap, renderScript is used in conjunction with Picasso library.

    public class Blur implements Transformation {
        protected static final int UP_LIMIT = 25;
        protected static final int LOW_LIMIT = 1;
        protected final Context context;
        protected final int blurRadius;
    
    
        public Blur(Context context, int radius) {
            this.context = context;
    
            if(radiusUP_LIMIT){
                this.blurRadius = UP_LIMIT;
            }else
                this.blurRadius = radius;
        }
    
        @Override
        public Bitmap transform(Bitmap source) {
            Bitmap sourceBitmap = source;
    
            Bitmap blurredBitmap;
            blurredBitmap = Bitmap.createBitmap(sourceBitmap);
    
            RenderScript renderScript = RenderScript.create(context);
    
            Allocation input = Allocation.createFromBitmap(renderScript, 
                    sourceBitmap, 
                    Allocation.MipmapControl.MIPMAP_FULL, 
                    Allocation.USAGE_SCRIPT);
    
    
    
            Allocation output = Allocation.createTyped(renderScript, input.getType());
    
            ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(renderScript, 
                                        Element.U8_4(renderScript));
    
            script.setInput(input);
            script.setRadius(blurRadius);
    
            script.forEach(output);
            output.copyTo(blurredBitmap);
    
            source.recycle();
            return blurredBitmap;
        }
    
        @Override
        public String key() {
            return "blurred";
        }
    }
    

    Once you have added this class use the Picasso to blur the imageview or any bitmap

    Picasso.with(context).load("load-from-whatever-source").transform(new Blur(context, 20)).into("wherever");
    

    I found this answer in this blog.

提交回复
热议问题