这两天做Android APP时才发现,Android的控件在需要设置圆角属性时,好像不能像css那样设置radius的值来解决,感觉好复杂……百度了一圈,找了一个方法实践,特此记录下来。
1、扩展类型
package com.example.demo;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
public class RadiusImageView extends android.support.v7.widget.AppCompatImageView {
private Path path;
public RadiusImageView(Context context) {
super(context);
init(context);
}
public RadiusImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public RadiusImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
path = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
float width = getWidth();
float height = getHeight();
float rx = width * 0.5f; // 半径为宽度二分之一
float ry = height * 0.5f; // 半径为高度二分之一
// 正方形经处理后变为圆形
path.reset();
// 四个点位,如果半径小,则点位还需另行计算
path.moveTo(0.0f, height * 0.5f);
path.lineTo(width * 0.5f, 0.0f);
path.lineTo(width, height * 0.5f);
path.lineTo(width * 0.5f, height);
path.lineTo(0.0f, height * 0.5f);
path.addRoundRect(0.0f, 0.0f, width, height, rx, ry, Path.Direction.CW);
canvas.clipPath(path);
super.onDraw(canvas);
}
}
2、使用方法
在activity_main.xml使用方法如下:
- Code页面添加:
<com.example.demo.RadiusImageView
android:id="@+id/imageView"
/>
- Design页面添加:
效果展示: