package com.android.chmo.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 com.android.chmo.R;

public class RoundImageView extends android.support.v7.widget.AppCompatImageView {
    float width, height;
    int radius, radiusTopLeft, radiusTopRight, radiusBottomLeft, radiusBottomRight;

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

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

    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView);
        if (typedArray != null) {
            radiusTopLeft = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_radius_top_left, 0);
            radiusTopRight = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_radius_top_right, 0);
            radiusBottomLeft = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_radius_bottom_left, 0);
            radiusBottomRight = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_radius_bottom_right, 0);
            radius = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_riv_radius, 0);
            if (radius > 0) {
                radiusTopLeft = radiusTopRight = radiusBottomLeft = radiusBottomRight = radius;
            }
            typedArray.recycle();
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        width = getWidth();
        height = getHeight();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Path path = new Path();
        float radii[] = {radiusTopLeft, radiusTopLeft, radiusTopRight, radiusTopRight, radiusBottomRight, radiusBottomRight, radiusBottomLeft, radiusBottomLeft};
        path.addRoundRect(new RectF(0, 0, width, height), radii, Path.Direction.CCW);
        canvas.clipPath(path);
        super.onDraw(canvas);
    }
}
