功能
可以实现圆角的图片控件
代码
RoundedImageView
package com.example.myapplication.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import com.example.myapplication.R;
/**
* <pre>
* Created by zhuguohui
* Date: 2023/1/11
* Time: 10:39
* Desc:圆角图片
* 使用radius属性定义四个角的圆角
* 使用radius_top_left 定义左上角
* 使用radius_top_right 定义右上角
* 使用radius_bottom_left 定义左下角
* 使用radius_bottom_right 定义右下角
* 如果radius是宽高的一半。那么就是圆形图片了
* </pre>
*/
public class RoundedImageView extends androidx.appcompat.widget.AppCompatImageView {
private final float tlRadius;
private final float trRadius;
private final float brRadius;
private final float blRadius;
private Path path;
public RoundedImageView(Context context) {
this(context, null);
}
public RoundedImageView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RoundedImageView);
float radius = array.getDimension(R.styleable.RoundedImageView_radius, 0);
tlRadius = array.getDimension(R.styleable.RoundedImageView_radius_top_left, radius);
trRadius = array.getDimension(R.styleable.RoundedImageView_radius_top_right, radius);
brRadius = array.getDimension(R.styleable.RoundedImageView_radius_bottom_right, radius);
blRadius = array.getDimension(R.styleable.RoundedImageView_radius_bottom_left, radius);
setBackground(new ColorDrawable());
}
@Override
protected void onDraw(Canvas canvas) {
int save = canvas.save();
canvas.clipPath(path, Region.Op.INTERSECT);
super.onDraw(canvas);
canvas.restoreToCount(save);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
path = new Path();
RectF rectF = getRectF();
float[] readius = {tlRadius, tlRadius, trRadius, trRadius, brRadius, brRadius, blRadius, blRadius};
path.addRoundRect(rectF, readius, Path.Direction.CW);
}
private RectF getRectF() {
Rect rect = new Rect();
getDrawingRect(rect);
RectF rectF = new RectF(rect);
return rectF;
}
}
xml属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RoundedImageView">
<!--四个角的大小-->
<attr name="radius" format="dimension" />
<!-- 左上圆角大小-->
<attr name="radius_top_left" format="dimension" />
<!-- 右上圆角大小-->
<attr name="radius_top_right" format="dimension" />
<!-- 右下圆角大小-->
<attr name="radius_bottom_right" format="dimension" />
<!-- 左下圆角大小-->
<attr name="radius_bottom_left" format="dimension" />
</declare-styleable>
</resources>
使用
可以设置不同方向上的圆角
可以统一设置圆角
如果圆角是宽高的一半,就是圆形控件了