温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Android中实现一个高斯模糊效果

发布时间:2021-04-17 17:28:47 来源:亿速云 阅读:1434 作者:Leah 栏目:移动开发

这篇文章给大家介绍如何在Android中实现一个高斯模糊效果,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

1、使用Glide

Glide.with(this)
     .load(service.getImageUri())
     .dontAnimate()
     .error(R.drawable.error_img)
     // 设置高斯模糊
     .bitmapTransform(new BlurTransformation(this, 14, 3))
     .into(imageview);

适用场景:动态配置的背景图片

2、对图片高斯模糊,需要先将图片转成bitmap对象

mport android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
public class BlurBitmapUtil {
 // 图片缩放比例(即模糊度)
 private static final float BITMAP_SCALE = 0.4f;
 /**
  * @param context 上下文对象
  * @param image 需要模糊的图片
  * @return 模糊处理后的Bitmap
  */
 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
 public static Bitmap blurBitmap(Context context, Bitmap image, float blurRadius) {
  // 计算图片缩小后的长宽
  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内核对象
  RenderScript rs = RenderScript.create(context);
  // 创建一个模糊效果的RenderScript的工具对象
  ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
  // 由于RenderScript并没有使用VM来分配内存,所以需要使用Allocation类来创建和分配内存空间
  // 创建Allocation对象的时候其实内存是空的,需要使用copyTo()将数据填充进去
  Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
  Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
  // 设置渲染的模糊程度, 25f是最大模糊度
  blurScript.setRadius(blurRadius);
  // 设置blurScript对象的输入内存
  blurScript.setInput(tmpIn);
  // 将输出数据保存到输出内存中
  blurScript.forEach(tmpOut);
  // 将数据填充到Allocation中
  tmpOut.copyTo(outputBitmap);
  return outputBitmap;
 }
}

不推荐:使用bitmap,频繁操作的话比较耗性能。

3、使用高斯模糊遮罩,可以对指定区域进行模糊,不需要处理单张图片(推荐!!)

推荐一个github上的项目,亲测有效。https://github.com/mmin18/RealtimeBlurView

<com.github.mmin18.widget.RealtimeBlurView
      android:id="@+id/blurview"
      android:layout_width="match_parent"
      android:layout_height="210dp"
      android:visibility="gone"
      app:realtimeBlurRadius="5dp"
      app:realtimeOverlayColor="#00000000" />

关于如何在Android中实现一个高斯模糊效果就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI