Android开发中图片控件ImageView默认的样子是矩形,方方正正的。在我们实际的项目中,有时候这些方正的图片显得有些呆板,我们就需要其它样式的图片,比较圆形图片(The rounded picture), 常见的就是app中用户头像等。要得到圆形图片有很多方式,比如draw一个circle,也可以用切好的圆形图片做背景或者写一个xml实现圆角功能等 等。不过在项目中,如果我们有多个地方要把图片展示出圆形的,而且图片是从网络上取的,这种情况还一个个处理就麻烦了,我们可以定义个圆形图片组件 RoundImageView,然后在要用的地方把RoundImageView 当成ImageView一样使用就行了。我在最近做的项目中也用到了圆形图片,所以做个笔记,方便下次使用!
首先看我们定义的RoundImageView:
public class RoundImageView extends ImageView {
private int mBorderThickness = 0;
private Context mContext;
private int defaultColor = 0xFFFFFFFF;
// 如果只有其中一个有值,则只画一个圆形边框
private int mBorderOutsideColor = 0;
private int mBorderInsideColor = 0;
// 控件默认长、宽
private int defaultWidth = 0;
private int defaultHeight = 0;
public RoundImageView(Context context) {
super(context);
mContext = context;
}
public RoundImageView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setCustomAttributes(attrs);
}
public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
setCustomAttributes(attrs);
}
private void setCustomAttributes(AttributeSe