Java 如何在 Android 中模糊背景图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31641973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to blur background images in Android
提问by heloisasim
采纳答案by Sandro Machado
The easiest way to do that is use a library. Take a look at this one: https://github.com/wasabeef/Blurry
最简单的方法是使用库。看看这个:https: //github.com/wasabeef/Blurry
With the library you only need to do this:
使用库,您只需要执行以下操作:
Blurry.with(context)
.radius(10)
.sampling(8)
.color(Color.argb(66, 255, 255, 0))
.async()
.onto(rootView);
回答by Geetha
You can have a view with Background color as black and set alpha for the view as 0.7 or whatever as per your requirement.
您可以将视图的背景颜色设置为黑色,并将视图的 alpha 设置为 0.7 或根据您的要求设置任何值。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/onboardingimg1">
<View
android:id="@+id/opacityFilter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
android:layout_alignParentBottom="true"
android:alpha="0.7">
</View>
</RelativeLayout>
回答by IntelliJ Amiya
An overlay
is an extra layer that sits on top of a View (the "host view") which is drawn after all other content in that view (including children, if the view is a ViewGroup). Interaction with the overlay layer is done by adding and removing drawables.
Try this ,Overlay with User Instructions
Anoverlay
是位于视图(“宿主视图”)之上的额外层,该层在该视图中的所有其他内容(包括子视图,如果视图是一个 ViewGroup)之后绘制。与覆盖层的交互是通过添加和删除可绘制对象来完成的。试试这个,覆盖用户说明
回答by Aparna Venkata
This might be a very late reply but I hope it helps someone.
这可能是一个很晚的回复,但我希望它可以帮助某人。
- You can use third party libs such as RenderScript/Blurry/etc.
- If you do not want to use any third party libs, you can do the below using alpha(setting alpha to 0 means complete blur and 1 means same as existing).
- 您可以使用第三方库,例如 RenderScript/Blurry/等。
- 如果您不想使用任何第三方库,您可以使用 alpha 执行以下操作(将 alpha 设置为 0 表示完全模糊,1 表示与现有相同)。
Note(If you are using point 2): While setting alpha to the background, it will blur the whole layout. To avoid this, create a new xml containing drawable and set alpha here to 0.5 (or value of your wish) and use this drawable name (name of file) as the background.
注意(如果您使用第 2 点):将 alpha 设置为背景时,它会模糊整个布局。为避免这种情况,请创建一个包含 drawable 的新 xml,并将此处的 alpha 设置为 0.5(或您希望的值),并使用此 drawable 名称(文件名)作为背景。
For example, use it as below (say file name is bgndblur.xml):
例如,如下使用它(假设文件名为 bgndblur.xml):
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shape="rectangle"
android:src="@drawable/registerscreenbackground"
android:alpha="0.5">
Use the below in your layout :
在您的布局中使用以下内容:
<....
android:background="@drawable/bgndblur">
Hope this helped.
希望这有帮助。
回答by navid
this might not be the most efficient solution but I had to use it since the wasabeef/Blurry library didn't work for me. this could be handy if you intend to have some getting-blurry animation:
这可能不是最有效的解决方案,但我不得不使用它,因为 wasabeef/Blurry 库对我不起作用。如果您打算制作一些模糊的动画,这可能会很方便:
1- you need to have 2 versions of the picture, normal one and the blurry one u make with photoshop or whatever
1- 你需要有 2 个版本的图片,正常的一个和你用 photoshop 或其他工具制作的模糊的一个
2- set the images fit on each other in your xml, then one of them could be seen and that's the upper one
2-在您的xml中设置彼此适合的图像,然后可以看到其中之一,那就是上面的
3- set fadeout animation on the upper one:
3- 在上面设置淡出动画:
final Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(1000);
fadeOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {upperone.setVisibility(View.GONE);}
@Override
public void onAnimationRepeat(Animation animation) {}
});
upperone.startAnimation(fadeOut);
回答by Jorge Casariego
This is an easy way to blur Images Efficiently with Android's RenderScript that I found on this article
这是使用我在本文中找到的 Android RenderScript 有效模糊图像的简单方法
Create a Class called 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; } }
Copy any image to your drawable folder
Use BlurBuilder in your activity like this:
@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));
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)
defaultConfig { ... renderscriptTargetApi *your target api* renderscriptSupportModeEnabled true }
Result
创建一个名为 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; } }
将任何图像复制到可绘制文件夹
在您的活动中使用 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));
Renderscript 包含在支持 v8 中,使这个答案能够下降到 api 8。要使用 gradle 启用它,请将这些行包含到您的 gradle 文件中(来自这个答案)
defaultConfig { ... renderscriptTargetApi *your target api* renderscriptSupportModeEnabled true }
结果
回答by Sachin Varma
The simplest way to achieve this is given below,
下面给出了实现此目的的最简单方法,
I)
一世)
Glide.with(context.getApplicationContext())
.load(Your Path)
.override(15, 15) // (change according to your wish)
.error(R.drawable.placeholder)
.into(image.score);
else you can follow the code below..
否则你可以按照下面的代码..
II)
二)
1.Create a class.(Code is given below)
1.创建一个类。(代码如下)
public class BlurTransformation extends BitmapTransformation {
private RenderScript rs;
public BlurTransformation(Context context) {
super( context );
rs = RenderScript.create( context );
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
Bitmap blurredBitmap = toTransform.copy( Bitmap.Config.ARGB_8888, true );
// Allocate memory for Renderscript to work with
Allocation input = Allocation.createFromBitmap(
rs,
blurredBitmap,
Allocation.MipmapControl.MIPMAP_FULL,
Allocation.USAGE_SHARED
);
Allocation output = Allocation.createTyped(rs, input.getType());
// Load up an instance of the specific script that we want to use.
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setInput(input);
// Set the blur radius
script.setRadius(10);
// Start the ScriptIntrinisicBlur
script.forEach(output);
// Copy the output to the blurred bitmap
output.copyTo(blurredBitmap);
toTransform.recycle();
return blurredBitmap;
}
@Override
public String getId() {
return "blur";
}
}
2.Set image to ImageView using Glide.
2.使用 Glide 将图像设置为 ImageView。
eg:
例如:
Glide.with(this)
.load(expertViewDetailsModel.expert.image)
.asBitmap()
.transform(new BlurTransformation(this))
.into(ivBackground);
回答by luttu android
You can use
您可以使用
Glide.with(getContext()).load(R.mipmap.bg)
.apply(bitmapTransform(new BlurTransformation(22)))
.into((ImageView) view.findViewById(R.id.imBg));
回答by Anil Makwana
Try below code.. Put This Code in On Create..
试试下面的代码..把这个代码放在创建中..
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Url="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTIur0ueOsmVmFVmAA-SxcCT7bTodZb3eCNbiShIiP9qWCWk3mDfw";
// Picasso.with(getContext()).load(Url).into(img_profile);
// Picasso.with(getContext()).load(Url).into(img_c_profile);
bitmap=getBitmapFromURL(Url);
Bitmap blurred = blurRenderScript(bitmap, 12);//second parametre is radius
img_profile.setImageBitmap(blurred);
Create Below Methods.. Just Copy Past..
创建下面的方法..只需复制过去..
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
@SuppressLint("NewApi")
private Bitmap blurRenderScript(Bitmap smallBitmap, int radius) {
try {
smallBitmap = RGB565toARGB888(smallBitmap);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bitmap = Bitmap.createBitmap(
smallBitmap.getWidth(), smallBitmap.getHeight(),
Bitmap.Config.ARGB_8888);
RenderScript renderScript = RenderScript.create(getActivity());
Allocation blurInput = Allocation.createFromBitmap(renderScript, smallBitmap);
Allocation blurOutput = Allocation.createFromBitmap(renderScript, bitmap);
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript,
Element.U8_4(renderScript));
blur.setInput(blurInput);
blur.setRadius(radius); // radius must be 0 < r <= 25
blur.forEach(blurOutput);
blurOutput.copyTo(bitmap);
renderScript.destroy();
return bitmap;
}
private Bitmap RGB565toARGB888(Bitmap img) throws Exception {
int numPixels = img.getWidth() * img.getHeight();
int[] pixels = new int[numPixels];
//Get JPEG pixels. Each int is the color values for one pixel.
img.getPixels(pixels, 0, img.getWidth(), 0, 0, img.getWidth(), img.getHeight());
//Create a Bitmap of the appropriate format.
Bitmap result = Bitmap.createBitmap(img.getWidth(), img.getHeight(), Bitmap.Config.ARGB_8888);
//Set RGB pixels.
result.setPixels(pixels, 0, result.getWidth(), 0, 0, result.getWidth(), result.getHeight());
return result;
}
回答by Nosiku Minyoi
You can quickly get to blur effect by doing the following.
您可以通过执行以下操作快速获得模糊效果。
// Add this to build.gradle app //
// 将此添加到 build.gradle 应用程序 //
Compile ' com.github.jgabrielfreitas:BlurImageView:1.0.1 '
// Add to XML
// 添加到 XML
<com.jgbrielfreitas.core.BlurImageView
android:id="@+id/iv_blur_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
//Add this to java
//将此添加到java
Import com.jgabrielfreitas.core.BlueImageView;
// Under public class *activity name * //
// 在公共类 *活动名称 * //
BlurImageView myBlurImage;
// Under Oncreate//
// 在 Oncreate 下//
myBlurImage = (ImageView) findViewById(R.id.iv_blur_image)
MyBlurImage.setBlue(5)
I hope that helps someone
我希望能帮助某人