Как сделать эффект размытия в android?

Пользователь

от aaron_armstrong , в категории: Другие , 6 месяцев назад

Как сделать эффект размытия в android?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp

1 ответ

Пользователь

от ransom_homenick , 6 месяцев назад

@aaron_armstrong 

В Android можно создать эффект размытия с помощью фильтров. Вот пример кода, демонстрирующего, как добавить размытие к изображению:

  1. Создайте XML-файл для размытия (например, blur.xml) в папке res/values/:
1
2
3
4
5
6
7
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="customBlurRadius" format="float"/>
    <declare-styleable name="CustomBlurView">
        <attr name="customBlurRadius"/>
    </declare-styleable>
</resources>


  1. В вашем layout-файле добавьте пользовательский вид (например, CustomBlurView):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.CustomBlurView
        android:id="@+id/customBlurView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/my_image"
        app:customBlurRadius="10" />

</RelativeLayout>


  1. Создайте пользовательский класс CustomBlurView, который наследует от ImageView:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;

public class CustomBlurView extends androidx.appcompat.widget.AppCompatImageView {
    private float blurRadius;

    public CustomBlurView(Context context) {
        super(context);
        init(context, null);
    }

    public CustomBlurView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CustomBlurView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        if (attrs != null) {
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomBlurView);
            blurRadius = ta.getFloat(R.styleable.CustomBlurView_customBlurRadius, 0);
            ta.recycle();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        BitmapDrawable drawable = (BitmapDrawable) getDrawable();
        if (drawable == null) {
            super.onDraw(canvas);
            return;
        }

        Bitmap bitmap = drawable.getBitmap();
        Bitmap blurredBitmap = applyBlur(bitmap, blurRadius);

        canvas.drawBitmap(blurredBitmap, 0, 0, null);
    }

    private Bitmap applyBlur(Bitmap bitmap, float blurRadius) {
        Bitmap blurredBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(blurredBitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        canvas.drawBitmap(bitmap, 0, 0, paint);

        PorterDuffXfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
        paint.setXfermode(xfermode);

        canvas.drawBitmap(bitmap, 0, 0, paint);

        return blurredBitmap;
    }

    public void setBlurRadius(float blurRadius) {
        this.blurRadius = blurRadius;
        invalidate();
    }
}


Теперь, когда вы используете свой пользовательский вид CustomBlurView вместо обычного ImageView, фон будет размытым с заданным радиусом.