常用工具类记录
java 代码
public class RoundImageView extends ImageView {
float width, height;
private int leftTopRadius;
private int rightTopRadius;
private int leftBottomRadius;
private int rightBottomRadius;
private int defaultRadius = 6;
private int radius;
private Context mContext;
public RoundImageView(Context context) {
this(context, null);
mContext = context;
}
public RoundImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
mContext = context;
init(context, attrs);
}
public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
if (Build.VERSION.SDK_INT < 18) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
@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();
}
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Round_Angle_Image_View);
radius = typedArray.getDimensionPixelOffset(R.styleable.Round_Angle_Image_View_radius, defaultRadius);
leftTopRadius = typedArray.getDimensionPixelOffset(R.styleable.Round_Angle_Image_View_left_top_radius, defaultRadius);
rightTopRadius = typedArray.getDimensionPixelOffset(R.styleable.Round_Angle_Image_View_right_top_radius, defaultRadius);
leftBottomRadius = typedArray.getDimensionPixelOffset(R.styleable.Round_Angle_Image_View_left_bottom_radius, defaultRadius);
rightBottomRadius = typedArray.getDimensionPixelOffset(R.styleable.Round_Angle_Image_View_right_bottom_radius, defaultRadius);
if (leftTopRadius == defaultRadius) {
leftTopRadius = radius;
}
if (rightTopRadius == defaultRadius) {
rightTopRadius = radius;
}
if (leftBottomRadius == defaultRadius) {
leftBottomRadius = radius;
}
if (rightBottomRadius == defaultRadius) {
rightBottomRadius = radius;
}
typedArray.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
Path path = new Path();
float rids[] = {leftTopRadius, leftTopRadius, rightTopRadius, rightTopRadius, leftBottomRadius, leftBottomRadius, rightBottomRadius, rightBottomRadius};
path.addRoundRect(new RectF(0, 0, width, height), rids, Path.Direction.CW);
canvas.clipPath(path);
super.onDraw(canvas);
}
}
自定义属性
<!-- 自定义四角矩形ImageView 的四个圆角属性 -->
<declare-styleable name="Round_Angle_Image_View">
<attr name="left_top_radius" format="dimension"/>
<attr name="right_top_radius" format="dimension"/>
<attr name="left_bottom_radius" format="dimension"/>
<attr name="right_bottom_radius" format="dimension"/>
<attr name="radius" format="dimension"/>
</declare-styleable>
使用
<com.xxx.RoundImageView
android:scaleType="centerCrop"
roundiv:radius="6dp"
android:layout_width="match_parent"
android:layout_height="match_parent"/>