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
| 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.util.Log;
import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatImageView;
public class RoundImageView extends AppCompatImageView { private static final String TAG = "RoundImageView";
private int radius = 0;
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); setup(context, attrs, defStyleAttr); }
private void setup(Context context, AttributeSet attrs, int defStyleAttr) { try { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView); radius = a.getDimensionPixelSize(R.styleable.RoundImageView_riv_radius, 0); Log.d(TAG, "RoundImageView: radius=" + radius); a.recycle(); } catch (Exception e) { e.printStackTrace(); } }
public void setRadius(int radius) { this.radius = radius; }
@Override protected void onDraw(Canvas canvas) { if (radius > 0) { Path path = new Path(); path.addRoundRect(new RectF(0, 0, getWidth(), getHeight()), radius, radius, Path.Direction.CW); canvas.clipPath(path); } super.onDraw(canvas); } }
|