1 前言
有时项目中用ImageView显示图片时需要把形状显示成圆角矩形。因为直角的太生硬了,体验不太友好。为此我们可以自定义一个ImageView来实现。
2 思路
我们自定义一个RoundCornerImageView类继承ImageView,通过改变在onDraw()方法中改变最终绘制的形状。
3 实现
下面直接上代码:
xml,attrs.xml:
<declare-styleable name="RoundCornerImageView">
<attr name="corner_size" format="integer" />
</declare-styleable>
java:
public class RoundCornerImageView extends ImageView {
private int cornerSize;//圆角大小
public RoundCornerImageView(Context context){
this(context,null);
}
public RoundCornerImageView(Context context, AttributeSet attrs){
this(context,attrs,0);
}
public RoundCornerImageView(Context context, AttributeSet attrs,int defStyle){
super(context,attrs,defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundCornerImageView,defStyle,0);
cornerSize = a.getInt(R.styleable.RoundCornerImageView_corner_size,5);
}
@Override
protected void onDraw(Canvas canvas) {
Path path = new Path();
int w = getWidth();
int h = getHeight();
//这里对path添加一个圆角区域,这里一般需要将dp转换为pixel
path.addRoundRect(new RectF(0,0,w,h), DensityUtil.dip2px(cornerSize),DensityUtil.dip2px(cornerSize), Path.Direction.CW);
canvas.clipPath(path);//将Canvas按照上面的圆角区域截取
super.onDraw(canvas);
}
/**
* 设置圆角的大小
* @param size
*/
public void setCornerSize(int size){
cornerSize = size;
}
}
4 使用
使用很简单,这里分为java代码中了xml中
java代码:
private RoundCornerImageView imageView;
imageView = new RoundCornerImageView(context);
mageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setCornerSize(10);
imageView.setImageResource(xxx);
xml中:
<xxx.xxx.RoundCornerImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:corner_size="10"/>
注意,需要引入相应的命名空间
xmlns:app="http://schemas.android.com/apk/res-auto"