Create Blurry Transparent Background Effect

Create blurry transparent background effect

Now that the window flag is deprecated, you've got to blur yourself. I answered this elsewhere but here is how you can blur a view:

You can now use ScriptIntrinsicBlur from the RenderScript library to blur quickly. Here is how to access the RenderScript API. The following is a class I made to blur Views and Bitmaps:

import android.support.v8.renderscript.*;

public class BlurBuilder {
private static final float BITMAP_SCALE = 0.4f;
private static final float BLUR_RADIUS = 7.5f;

public static Bitmap blur(View v) {
return blur(v.getContext(), getScreenshot(v));
}

public static Bitmap blur(Context ctx, 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(ctx);
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;
}

private static Bitmap getScreenshot(View v) {
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
}

To apply this to a fragment, add the following to onCreateView:

final Activity activity = getActivity();
final View content = activity.findViewById(android.R.id.content).getRootView();
if (content.getWidth() > 0) {
Bitmap image = BlurBuilder.blur(content);
window.setBackgroundDrawable(new BitmapDrawable(activity.getResources(), image));
} else {
content.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Bitmap image = BlurBuilder.blur(content);
window.setBackgroundDrawable(new BitmapDrawable(activity.getResources(), image));
}
});
}

NOTE: This solution requires min sdk to be API 17

EDIT: Renderscript is included into support v8 enabling this answer down to api 8. To enable it using gradle include these lines into your gradle file (from this answer) and use Renderscript from package android.support.v8.renderscript:

android {
...
defaultConfig {
...
renderscriptTargetApi *your target api*
renderscriptSupportModeEnabled true
}
...
}

How can I make a CSS glass/blur effect work for an overlay?

I was able to piece together information from everyone here and further Googling, and I came up with the following which works in Chrome and Firefox: http://jsfiddle.net/xtbmpcsu/. I'm still working on making this work for IE and Opera.

The key is putting the content inside of the div to which the filter is applied:





body {
background: #300000;
background: linear-gradient(45deg, #300000, #000000, #300000, #000000);
color: white;
}
#mask {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: black;
opacity: 0.5;
}
img {
filter: blur(10px);
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);
position: absolute;
left: 100px;
top: 100px;
height: 300px;
width: auto;
}
<div id="mask">
<p>Lorem ipsum ...</p>
<img src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />
</div>

How to achieve a blur effect on navbar?

It's done by a mix of setting opacity to the background color, and adding a blur filter.

For the example below, take a look at background:rgba(0,0,0,.7) and backdrop-filter: blur(5px).

For background color, you must use RBGA instead of hex. Adjust the .7 at the end to customize opacity. Similarly with blur filter, adjust the (5px) for intensity of blur.





.navbar {

background:rgba(0,0,0,.7);

backdrop-filter: blur(5px);


color:#fff;position:fixed;height:300px;width:500px}

img {position:fixed}
<img src="https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">


<div class="navbar">

transparent black background

</div>

How create transparent view with with blur effect?

I found an excellent tutorial that might help you to create a smooth transparent view with blur effect: https://www.raywenderlich.com/167-uivisualeffectview-tutorial-getting-started

CSS Blur Effect and Background Color

You can use @supports to selectively apply your styles based on browser support:

    .transparent-header {
background-color: rgba(0,0,0,0.9);
}

@supports (-webkit-backdrop-filter: blur(1px)) or (backdrop-filter: blur(1px))
.transparent-header {
background-color: rgba(0,0,0,0.5);
-webkit-backdrop-filter: blur(20px);
backdrop-filter: blur(20px);
}
}

Transparent blurry view which blurs layout underneath

This was on my mind for some time, and I just implemented it thanks to your question.

To be able to do this, we need to draw the layout that is beneath our blur layout into a bitmap. Than by using a blurring algorithm, we need to blur that bitmap and finally draw blurred bitmap as our blur layout's background.

Luckily android has cached drawing mechanism, so first part is easy. We can simply enable cached drawing for our beneath layout and use getDrawingCache() to acquire the bitmap from it.

Now we need a fast blurring algorithm. I used this https://stackoverflow.com/a/10028267/3133545

Here it is.

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);
}

}

Usage :

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

BlurDrawable blurDrawable = new BlurDrawable(beneathView, radius);

blurView.setBackgroundDrawable(blurDrawable);

And how my test application looked like:

test application

I decided not to use this tho, because it is too hacky and not looking as cool as i thought it would be in first place.

How to make an activity background transparent and blur the background


how to blur the background?

You can use RenderScript available in support library

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;
}
}

see this link for more details

Or you can use Blurry

Does anyone has an idea where is the code in android to do that?

For taking screenshot of your app screen see this link

How to blur the background behind a control

If want to blur the image behind the Button (or a transparent control in general) you have to follow a different approach.

You need the exact tile of the image in order to blur it using the BlurEffect.

In order to not blur the Button itself, you must add alayer beneath the button that has the BlurEffect applied.

The following example extends a ContentControl named BlurHost that renders the Content e.g., the Button, on top of a Border element that will actualy blur the background using a VisualBrush.

The brush itself has a tile defined that is located at the position of the BlurHost which hosts the Button (or any other transparent control).

The basic steps to implement a blurred background:

  1. Add the background image
  2. Create a blur layer beneath the element
  3. Get the bounds of the element e.g., the Button which is located relative to the parent of the Image (preferably the root container)
  4. Use the bounding rectangle to define the tile of the VisualBrush (the actual section of the image)
  5. Apply the brush on the blur layer

Usage example

MainWindow.xaml

<Window>
<!-- Allow the root grid to stretch accross the Window -->
<Grid>
<Image x:Name="img" Source="/someImage.png" />

<!--
Optionally override the default BlurEffect
by setting the BlurHost.BlurEffect property
-->
<local:BlurHost BlurBackground="{Binding ElementName=img}"
BlurOpacity="1"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<Button Background="Transparent"
FontSize="48"
Content="Acquista ora- $23.99" />
</local:BlurHost>
</Grid>
</Window>

Sample Image

Implementation example

The implementation is simple. You have to add property changed handlers in order to make the control dynamic.

BlurHost.cs

The ContentControl serves as a container. The blurred background is visible at the transparent areas of the content.

public class BlurHost : ContentControl
{
public Visual BlurBackground
{
get => (Visual)GetValue(BlurBackgroundProperty);
set => SetValue(BlurBackgroundProperty, value);
}

public static readonly DependencyProperty BlurBackgroundProperty =
DependencyProperty.Register(
"BlurBackground",
typeof(Visual),
typeof(BlurHost),
new PropertyMetadata(default(Visual), OnBlurBackgroundChanged));

public double BlurOpacity
{
get => (double)GetValue(BlurOpacityProperty);
set => SetValue(BlurOpacityProperty, value);
}

public static readonly DependencyProperty BlurOpacityProperty =
DependencyProperty.Register(
"BlurOpacity",
typeof(double),
typeof(BlurHost),
new PropertyMetadata(1.0));

public BlurEffect BlurEffect
{
get => (BlurEffect)GetValue(BlurEffectProperty);
set => SetValue(BlurEffectProperty, value);
}

public static readonly DependencyProperty BlurEffectProperty =
DependencyProperty.Register(
"BlurEffect",
typeof(BlurEffect),
typeof(BlurHost),
new PropertyMetadata(
new BlurEffect()
{
Radius = 10,
KernelType = KernelType.Gaussian,
RenderingBias = RenderingBias.Performance
}));

private Border PART_BlurDecorator { get; set; }
private VisualBrush BlurDecoratorBrush { get; set; }

static BlurHost()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(BlurHost), new FrameworkPropertyMetadata(typeof(BlurHost)));
}

public BlurHost()
{
Loaded += OnLoaded;

// TODO::Update Opacity of VisualBrush when property BlurOpacity changes
this.BlurDecoratorBrush = new VisualBrush()
{
ViewboxUnits = BrushMappingMode.Absolute,
Opacity = this.BlurOpacity
};
}

private void DrawBlurredElementBackground()
{
if (!TryFindVisualRootContainer(this, out FrameworkElement rootContainer))
{
return;
}

// Get the section of the image where the BlurHost element is located
Rect elementBounds = TransformToVisual(rootContainer)
.TransformBounds(new Rect(this.RenderSize));

// Use the section bounds to actually "cut out" the image tile
this.BlurDecoratorBrush.Viewbox = elementBounds;
}

private void OnLoaded(object sender, RoutedEventArgs e)
{
if (TryFindVisualRootContainer(this, out FrameworkElement rootContainer))
{
rootContainer.SizeChanged += OnRootContainerElementResized;
}

DrawBlurredElementBackground();
}

public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.PART_BlurDecorator = GetTemplateChild("PART_BlurDecorator") as Border;
this.PART_BlurDecorator.Effect = this.BlurEffect;
this.PART_BlurDecorator.Background = this.BlurDecoratorBrush;
}

private static void OnBlurBackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var this_ = d as BlurHost;
this_.BlurDecoratorBrush.Visual = e.NewValue as Visual;
this_.DrawBlurredElementBackground();
}

private void OnRootContainerElementResized(object sender, SizeChangedEventArgs e)
=> DrawBlurredElementBackground();

private bool TryFindVisualRootContainer(DependencyObject child, out FrameworkElement rootContainerElement)
{
rootContainerElement = null;
DependencyObject parent = VisualTreeHelper.GetParent(child);
if (parent == null)
{
return false;
}

if (parent is not Window visualRoot)
{
return TryFindVisualRootContainer(parent, out rootContainerElement);
}

rootContainerElement = visualRoot.Content as FrameworkElement;
return true;
}
}

Generic.xaml

The default Style for the BlurHost. The Generic.xaml file is located in the Themes folder of the application (project).

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Net.Wpf">

<Style TargetType="local:BlurHost">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:BlurHost">
<Grid>

<!-- Blur layer beneath the hosted element (ContentPresenter) -->
<Border x:Name="PART_BlurDecorator"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"/>
<ContentPresenter />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>


Related Topics



Leave a reply



Submit