欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android高斯模糊实现方案

程序员文章站 2022-11-06 17:14:21
适用场景:动态配置的背景图片 不推荐:使用bitmap,频繁操作的话比较耗性能。 3、使用高斯模糊遮罩,可以对指定区域进行模糊,不需要处理单张图片(推荐!!) 推荐一个github上的项目,亲测有效。https://github.com/mmin18/RealtimeBlurView
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" />

 

app:realtimeoverlaycolor="#00000000",这里设置成透明色,效果就如同直接对图片进行高斯模糊。