package com.tencent.liteav.demo.superplayer.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.tencent.liteav.demo.superplayer.R;


public class RoundImageView extends androidx.appcompat.widget.AppCompatImageView {
    private float topLeftRadius;
    private float topRightRadius;
    private float bottomLeftRadius;
    private float bottomRightRadius;

    public RoundImageView(Context context) {
        this(context, null);
    }

    public RoundImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView, defStyleAttr, 0);
            float radius = a.getDimension(R.styleable.RoundImageView_radius, 0f);
            topLeftRadius = a.getDimension(R.styleable.RoundImageView_topLeftRadius, radius);
            topRightRadius = a.getDimension(R.styleable.RoundImageView_topRightRadius, radius);
            bottomLeftRadius = a.getDimension(R.styleable.RoundImageView_bottomLeftRadius, radius);
            bottomRightRadius = a.getDimension(R.styleable.RoundImageView_bottomRightRadius, radius);
            a.recycle();
        }
    }


    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();
        canvas.clipPath(getClipPath(getWidth(), getHeight()));
        super.onDraw(canvas);
        canvas.restore();
    }

    private Path getClipPath(int width, int height) {
        final Path path = new Path();
        float[] radiusArray = new float[]{
                topLeftRadius, topLeftRadius, topRightRadius, topRightRadius,
                bottomRightRadius, bottomRightRadius, bottomLeftRadius, bottomLeftRadius
        };
        path.addRoundRect(new RectF(0, 0, width, height), radiusArray, Path.Direction.CW);

        return path;
    }
}
