49

我有一个透明的线性布局,现在我正在寻找一种方法给它一个模糊效果,所以它下面的东西会变得模糊。就像 Windows 7 Aero 的外观(见截图)。

我知道你可以做这样的模糊效果:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

但这仅适用于出现对话框时模糊背景。

我已经在谷歌上搜索了将近一个小时,但我找不到任何东西。有人对如何做到这一点有任何建议吗?

谢谢

Windows 7 Aero 效果

4

6 回答 6

71

在 android 上实时模糊仍然是一个障碍。以下是一些可行机制之间的综合比较:

StackBlurOnur (已经在名字下的答案中列出fastBlur):

它的外观(在半径 20 处):

在此处输入图像描述

生成每个记录的时间(毫秒)BitmapDrawable

I/(10266): Total time taken: 35
I/(10266): Total time taken: 54
I/(10266): Total time taken: 48
I/(10266): Total time taken: 36
I/(10266): Total time taken: 48
I/(10266): Total time taken: 39
I/(10266): Total time taken: 49
I/(10266): Total time taken: 50
I/(10266): Total time taken: 35
I/(10266): Total time taken: 47

平均 => ~ 44.1 毫秒 => 每秒 22 个可绘制对象

渲染脚本

ScriptIntrinsicBlur提供始终如一的快速模糊。它使用支持库提供的 api 8 及更高版本。

它的样子(在半径 20 处):

在此处输入图像描述

生成每个记录的时间(毫秒)BitmapDrawable

I/(9342): Total time taken: 14
I/(9342): Total time taken: 16
I/(9342): Total time taken: 13
I/(9342): Total time taken: 28
I/(9342): Total time taken: 14
I/(9342): Total time taken: 12
I/(9342): Total time taken: 14
I/(9342): Total time taken: 19
I/(9342): Total time taken: 13
I/(9342): Total time taken: 13

平均 => ~ 15.6 毫秒 => 每秒 64 个可绘制对象

渲染脚本(半径 = 3)+ 缩放(20%)

这是另一种获得体面(?)但快速模糊的方法。我们所做的是将位图缩放到其大小的一小部分——比如 20%——并将模糊算法应用于缩小的版本。完成后,我们将位图缩放到其原始大小。结果不如在原版上使用模糊算法,但还算过得去。另请注意,半径值不应太高,否则生成的位图将难以辨认。

它看起来像什么:

在此处输入图像描述

生成每个记录的时间(毫秒)BitmapDrawable

I/(11631): Total time taken: 5
I/(11631): Total time taken: 19
I/(11631): Total time taken: 3
I/(11631): Total time taken: 7
I/(11631): Total time taken: 7
I/(11631): Total time taken: 5
I/(11631): Total time taken: 7
I/(11631): Total time taken: 17
I/(11631): Total time taken: 5
I/(11631): Total time taken: 4

平均 => ~ 7.9 毫秒 => 每秒 126 个可绘制对象

StackBlur(半径 = 3)+ 缩放(20%)

与上面#3 相同的概念。将大小减小到 20% 并在缩放的位图上应用 stackblur。

在此处输入图像描述

I/(12690): Total time taken: 4
I/(12690): Total time taken: 20
I/(12690): Total time taken: 4
I/(12690): Total time taken: 4
I/(12690): Total time taken: 5
I/(12690): Total time taken: 5
I/(12690): Total time taken: 4
I/(12690): Total time taken: 21
I/(12690): Total time taken: 3
I/(12690): Total time taken: 4

平均 => ~ 7.4 毫秒 => 每秒 135 个可绘制对象

在 Nex4 上进行的测试。位图大小 - 200 像素 x 200 像素

另一个提示:方法buildDrawingCache()getDrawingCache()本身需要很长时间。另一种方法是使用您需要模糊的视图尺寸创建位图:

Bitmap toDrawOn = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);

// Create a canvas - assign `toDrawOn` as an offscreen bitmap to it
Canvas holdingCanvas = new Canvas(toDrawOn);

// Now, let the view draw itself on this canvas
yourView.draw(holdingCanvas);

视图现已绘制toDrawOn,您可以随意使用它。

根据我的经验,这比生成和访问视图的绘图缓存要快得多。

如果您在实施上述 4 种方法中的任何一种时需要帮助,请在评论中告诉我。

请记住,上面的 GIF 已被缩小等等。如果您想查看原始屏幕捕获 (mp4) 文件 - 请查看此链接

于 2014-05-29T06:50:17.213 回答
39

这在我脑海中有一段时间了,由于您的问题,我刚刚实现了它。

为此,我们需要将模糊布局下方的布局绘制为位图。与使用模糊算法相比,我们需要模糊该位图,最后绘制模糊位图作为我们的模糊布局的背景。

幸运的是 android 有缓存绘图机制,所以第一部分很容易。我们可以简单地为我们的下方布局启用缓存绘图,并getDrawingCache()从中获取位图。

现在我们需要一个快速的模糊算法。我用这个https://stackoverflow.com/a/10028267/3133545

这里是。

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;

import java.lang.ref.WeakReference;
import java.util.InputMismatchException;

/**
 * A drawable that draws the target view as blurred using fast blur
 * <p/>
 * <p/>
 * TODO:we might use setBounds() to draw only part a of the target view
 * <p/>
 * Created by 10uR on 24.5.2014.
 */
public class BlurDrawable extends Drawable {

    private WeakReference<View> targetRef;
    private Bitmap blurred;
    private Paint paint;
    private int radius;


    public BlurDrawable(View target) {
        this(target, 10);
    }

    public BlurDrawable(View target, int radius) {
        this.targetRef = new WeakReference<View>(target);
        setRadius(radius);
        target.setDrawingCacheEnabled(true);
        target.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_AUTO);
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
    }

    @Override
    public void draw(Canvas canvas) {
        if (blurred == null) {
            View target = targetRef.get();
            if (target != null) {
                Bitmap bitmap = target.getDrawingCache(true);
                if (bitmap == null) return;
                blurred = fastBlur(bitmap, radius);
            }
        }
        if (blurred != null && !blurred.isRecycled())
            canvas.drawBitmap(blurred, 0, 0, paint);
    }

    /**
     * Set the bluring radius that will be applied to target view's bitmap
     *
     * @param radius should be 0-100
     */
    public void setRadius(int radius) {
        if (radius < 0 || radius > 100)
            throw new InputMismatchException("Radius must be 0 <= radius <= 100 !");
        this.radius = radius;
        if (blurred != null) {
            blurred.recycle();
            blurred = null;
        }
        invalidateSelf();
    }


    public int getRadius() {
        return radius;
    }

    @Override
    public void setAlpha(int alpha) {
    }


    @Override
    public void setColorFilter(ColorFilter cf) {

    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    /**
     * from https://stackoverflow.com/a/10028267/3133545
     * <p/>
     * <p/>
     * <p/>
     * Stack Blur v1.0 from
     * http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
     * <p/>
     * Java Author: Mario Klingemann <mario at quasimondo.com>
     * http://incubator.quasimondo.com
     * created Feburary 29, 2004
     * Android port : Yahel Bouaziz <yahel at kayenko.com>
     * http://www.kayenko.com
     * ported april 5th, 2012
     * <p/>
     * This is a compromise between Gaussian Blur and Box blur
     * It creates much better looking blurs than Box Blur, but is
     * 7x faster than my Gaussian Blur implementation.
     * <p/>
     * I called it Stack Blur because this describes best how this
     * filter works internally: it creates a kind of moving stack
     * of colors whilst scanning through the image. Thereby it
     * just has to add one new block of color to the right side
     * of the stack and remove the leftmost color. The remaining
     * colors on the topmost layer of the stack are either added on
     * or reduced by one, depending on if they are on the right or
     * on the left side of the stack.
     * <p/>
     * If you are using this algorithm in your code please add
     * the following line:
     * <p/>
     * Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>
     */
    private static Bitmap fastBlur(Bitmap sentBitmap, int radius) {


        Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        Log.e("pix", w + " " + h + " " + pix.length);
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }

        bitmap.setPixels(pix, 0, w, 0, 0, w, h);

        return (bitmap);
    }

}

用法 :

View beneathView = //the view that beneath blur view
View blurView= //blur View

BlurDrawable blurDrawable = new BlurDrawable(beneathView, radius);

blurView.setBackgroundDrawable(blurDrawable);

以及我的测试应用程序的样子:

测试申请

我决定不使用它,因为它太老套了,而且看起来不像我想象的那么酷。

于 2014-05-24T01:35:26.333 回答
17

这是 GDE Mario Viviani的“使用 Renderscript 有效地模糊图像”的好方法。

这是复制/粘贴:

模糊图像是许多开发人员需要实现的效果,可能需要一些时间和精力来实现。此外,由于需要进行大量图像处理,因此如果编码不当,在 CPU 和内存使用方面可能会非常痛苦。

有一种快速有效的模糊图像解决方案,即Renderscript

自API 11 ( Honeycomb)起可用,Renderscript允许利用 GPU 加速并针对高性能 3D 渲染和计算操作。 Renderscript是一个非常复杂和清晰的产品,并且允许使用原生 C99 语言进行深度配置和编码,从而实现可移植性、性能和可用性。

但是,由于API 17 (4.2.2)Renderscript提供了一些执行定义明确的操作的内置函数,称为 Intrinsics。Intrinsics 是预先编写的脚本,允许执行模糊、Blen、矩阵卷积等操作,而无需编写Renderscript代码。

这是我写的一个简单的方法,可以轻松地有效地将模糊滤镜应用于位图:

public Bitmap blurBitmap(Bitmap bitmap) {

    //Let's create an empty bitmap with the same size of the bitmap we want to blur
    Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);

    //Instantiate a new Renderscript
    RenderScript rs = RenderScript.create(getApplicationContext());

    //Create an Intrinsic Blur Script using the Renderscript
    ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));

    //Create the in/out Allocations with the Renderscript and the in/out bitmaps
    Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
    Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);

    //Set the radius of the blur
    blurScript.setRadius(25.f);

    //Perform the Renderscript
    blurScript.setInput(allIn);
    blurScript.forEach(allOut);

    //Copy the final bitmap created by the out Allocation to the outBitmap
    allOut.copyTo(outBitmap);

    //recycle the original bitmap
    bitmap.recycle();

    //After finishing everything, we destroy the Renderscript.
    rs.destroy();

    return outBitmap;
}

RenderScript 模糊图像

还有……瞧!位图模糊!:-)

请记住,要运行之前的代码,您需要最低 API 17 (4.2.2)。

这是此方法的要点: https ://gist.github.com/Mariuxtheone/903c35b4927c0df18cf8

如果您想了解更多关于 Intrinsics 的信息,请查看 Android 开发者博客上的这篇文章: http ://android-developers.blogspot.it/2013/08/renderscript-intrinsics.html

如果您有兴趣了解有关 Renderscript 的更多信息,请查看以下链接: http : //android-developers.blogspot.it/2011/02/introducing-renderscript.html http://android-developers.blogspot.it/2011 /03/renderscript.html

于 2014-05-29T09:57:55.477 回答
0

使用布局功能不容易做到这一点。

我建议将父视图绘制到画布上,如下所述:如何使任何视图绘制到画布上?隐藏前景视图。然后,模糊画布并使用此数据作为背景或其中的一部分绘制前景视图。

如果您希望此效果生效,这将是非常耗费资源的操作。您至少应该尝试缓存模糊结果。

于 2014-03-19T12:02:15.960 回答
0

步骤 1. 剪切位图中需要模糊的背景图像部分。

步骤 2. 模糊位图的那部分。

步骤 3. 将位图设置为背景。

方法

private void applyBlur(final View image, final View layout) {
image.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            image.getViewTreeObserver().removeOnPreDrawListener(this);
            image.buildDrawingCache();

            Bitmap bmp = image.getDrawingCache();

            Bitmap overlay = Bitmap.createBitmap((int) (layout.getMeasuredWidth()),
                    (int) (layout.getMeasuredHeight()), Bitmap.Config.ARGB_8888);

            Canvas canvas = new Canvas(overlay);

            canvas.translate(-layout.getLeft(), -layout.getTop());
            canvas.drawBitmap(bmp, 0, 0, null);

            RenderScript rs = RenderScript.create(getActivity());

            Allocation overlayAlloc = Allocation.createFromBitmap(
                    rs, overlay);

            ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(
                    rs, overlayAlloc.getElement());

            blur.setInput(overlayAlloc);

            blur.setRadius(20);

            blur.forEach(overlayAlloc);

            overlayAlloc.copyTo(overlay);

            layout.setBackground(new BitmapDrawable(
                    getResources(), overlay));

            rs.destroy();
            return true;
        }
    });
}

...

现在调用这个函数:

调用方法

applyBlur(detail_main_image, titleLayout);

...

//其中detail_main_image是我必须在其上显示模糊部分的图像//并且titleLayout是我必须在其上设置背景模糊的视图。

于 2016-05-02T09:43:12.013 回答
0

如果您为此创建自定义视图,则可以使用maskFilter属性使视图模糊:

private val paint = Paint(ANTI_ALIAS_FLAG)
private val path = Path()

init {
    paint.maskFilter = BlurMaskFilter(15f, BlurMaskFilter.Blur.NORMAL)
}

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    ...
    canvas.drawPath(path, paint)
}
于 2021-09-20T14:31:27.380 回答