如何在 Android 中模糊背景图像

新手上路,请多包涵

像下图这样模糊背景图像的最佳方法是什么?我看到了一些代码和库,但它们已经有几年的历史了,或者像 BlurBehind 库,但它并没有产生同样的效果。提前致谢!

在此处输入图像描述

原文由 heloisasim 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 725
2 个回答

最简单的方法是使用库。看看这个: https ://github.com/wasabeef/Blurry

使用库你只需要这样做:

 Blurry.with(context)
  .radius(10)
  .sampling(8)
  .color(Color.argb(66, 255, 255, 0))
  .async()
  .onto(rootView);

原文由 Sandro Machado 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是我在 本文 中找到的使用 Android 的 RenderScript 有效模糊图像的简单方法

  1. 创建一个名为 BlurBuilder 的类
   public class BlurBuilder {
     private static final float BITMAP_SCALE = 0.4f;
     private static final float BLUR_RADIUS = 7.5f;

     public static Bitmap blur(Context context, Bitmap image) {
       int width = Math.round(image.getWidth() * BITMAP_SCALE);
       int height = Math.round(image.getHeight() * BITMAP_SCALE);

       Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
       Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);

       RenderScript rs = RenderScript.create(context);
       ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
       Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
       Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
       theIntrinsic.setRadius(BLUR_RADIUS);
       theIntrinsic.setInput(tmpIn);
       theIntrinsic.forEach(tmpOut);
       tmpOut.copyTo(outputBitmap);

       return outputBitmap;
     }
   }

  1. 将任何图像复制到您的可绘制文件夹

  2. 在您的活动中使用 BlurBuilder,如下所示:

    @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       requestWindowFeature(Window.FEATURE_NO_TITLE);
       getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
               WindowManager.LayoutParams.FLAG_FULLSCREEN);
       setContentView(R.layout.activity_login);

       mContainerView = (LinearLayout) findViewById(R.id.container);
       Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background);
       Bitmap blurredBitmap = BlurBuilder.blur( this, originalBitmap );
       mContainerView.setBackground(new BitmapDrawable(getResources(), blurredBitmap));

  1. Renderscript 包含在 support v8 中,使这个答案低至 api 8。要使用 gradle 启用它,请将这些行包含到你的 gradle 文件中(来自这个 答案
    defaultConfig {
       ...
       renderscriptTargetApi *your target api*
       renderscriptSupportModeEnabled true
   }

  1. 结果

在此处输入图像描述

原文由 Jorge Casariego 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题