Android:仅从左侧模糊图像

Android: Blur image from only left side

我想在我的应用中对背景图片应用模糊效果。我尝试了很多网上可用的解决方案和技巧,但它们只是模糊了整个图像,但我的要求是只从左边和底部模糊,有没有什么技巧可以做到这一点。任何帮助将不胜感激。

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample);

    LinearLayout blurimage = (LinearLayout) findViewById(R.id.bg);
    Bitmap blurimages = BlurImage(((BitmapDrawable) getResources().getDrawable(R.drawable.default_background)).getBitmap());
    blurimage.setBackground(new BitmapDrawable(blurimages));
}

@SuppressLint({"NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi"})
public Bitmap BlurImage(Bitmap input) {
    RenderScript rsScript = RenderScript.create(SampleActivity.this);
    Allocation alloc = Allocation.createFromBitmap(rsScript, input);
    ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rsScript, Element.U8_4(rsScript));
    blur.setRadius(10);
    blur.setInput(alloc);

    Bitmap result = Bitmap.createBitmap(input.getWidth(), input.getHeight(), input.getConfig());
    Allocation outAlloc = Allocation.createFromBitmap(rsScript, result);
    blur.forEach(outAlloc);
    outAlloc.copyTo(result);

    rsScript.destroy();
    return result;
}

如果您想模糊图像的某些部分,则需要在将其输入模糊算法之前剪切该部分。

你可以像这样从bitmap获得Canvasbitmap 必须是 mutable.

Canvas canvas = new Canvas(bitmap name);

要截取bitmap的一部分,我们需要一个Rect来指定我们感兴趣的子集,我们将其命名为srcRect。我们需要另一个 Rect,我们的原始位图将被缩放以适应其中,我们将其命名为 destRect.

声明你的模糊位图尺寸

 int blurBitmapWidth = 50;
 int blurBitmapHeight = 50;

声明你的矩形

 Bitmap original = decode form resources....
 Rect srcRect = new Rect(0, original.getHeight() - blurBitmapHeight, blurBitmapWidth, original.getHeight());  // bottom left portion
 Rect destRect = new Rect(0, 0, blurBitmapWidth, blurBitmapHeight);
 Bitmap croppedBitmap = cutBitmap(original, srcRect, destRect);

CutBitmap 方法

private Bitmap cutBitmap(final Bitmap originalBmp, Rect src, Rect dest) {
    Bitmap croppedBitmap = Bitmap.createBitmap(dest.width(), dest.height(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(croppedBitmap);
    canvas.drawBitmap(originalBmp, src, dest, null);
    return croppedBitmap;
}

现在 croppedBitmap 包含 original 的左下部分。将其输入模糊算法。

此外,如果您想在 original 上绘制模糊部分,则只需在 original bitmap 上获得一个 canvas,然后使用 srcRect 绘制 blurred bitmap

Canvas c = new Canvas(original);
c.drawBitmap(bitmap obtained from blur algorithm, srcRect.left, srcRect.top, null);