我正在尝试制作一个不仅具有透明背景而且还具有模糊效果的 View 。这样,下面的 View 似乎就失去了焦点。我希望它看起来像按住电源按钮后的屏幕。有什么想法吗?
最佳答案
现在窗口标志已被弃用,您必须模糊自己。我在其他地方回答了这个问题,但这里是如何模糊 View :
您现在可以使用 RenderScript 库中的 ScriptIntrinsicBlur 来快速模糊。 Here 是如何访问 RenderScript API。以下是我为模糊 View 和位图制作的一个类:
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;
}
}
要将其应用于 fragment ,请将以下内容添加到 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));
}
});
}
注意:此解决方案要求 min sdk 为 API 17
编辑: Renderscript 包含在支持 v8 中,可以将此答案降至 api 8。要使用 gradle 启用它,请将这些行包含到您的 gradle 文件中(从此 answer )并使用包 android.support.v8.renderscript 中的 Renderscript:
android {
...
defaultConfig {
...
renderscriptTargetApi *your target api*
renderscriptSupportModeEnabled true
}
...
}
关于android - 创建模糊透明背景效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6795483/