/**
* @author cgq
*
*/
public class NameRoundView extends ImageView{
private Paint mPaintBackground;
private Paint mPaintText;
private Rect mRect;
private String text;
private int charHash;
public NameRoundView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public NameRoundView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public NameRoundView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
}
/*温馨提示:自定义控件,先实现构造方法,第一中是程序内部实例化采用,传入context,第二种用于layout实例化,会把xml的参数通过AttributeSet带入Vie内
* 第三种主题的style信息,也从XML带入
* 自定义控件必须实现 onMeasure()---onLayout()--ondraw(),大多数核心代码在ondraw()内,
* */
//初始化画笔
private void init() {
mPaintBackground =new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintText = new Paint(Paint.ANTI_ALIAS_FLAG);
mRect = new Rect();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec); //宽高相同
}
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
// TODO Auto-generated method stub
super.onLayout(changed, left, top, right, bottom);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if (null != text) {
int color = colors[charHash % colors.length];
// 画圆
mPaintBackground.setColor(color);
canvas.drawCircle(getWidth() / 2, getWidth() / 2, getWidth() / 2, mPaintBackground);
// 写字
mPaintText.setColor(Color.WHITE);
mPaintText.setTextSize(getWidth() / 2);
mPaintText.setStrokeWidth(3);
mPaintText.getTextBounds(text, 0, 1, mRect);
// 垂直居中
Paint.FontMetricsInt fontMetrics = mPaintText.getFontMetricsInt();
int baseline = (getMeasuredHeight() - fontMetrics.bottom - fontMetrics.top) / 2;
// 左右居中
mPaintText.setTextAlign(Paint.Align.CENTER);
canvas.drawText(text, getWidth() / 2, baseline, mPaintText);
}
}
//暴露给外部的方法
public void setTextName(String content) {
if (content == null) {
content=" ";
}
this.text = String.valueOf(content.toCharArray()[0]);
this.text = text.toUpperCase();
charHash = this.text.hashCode();
// 重绘
invalidate();
}
//使用
NameRoundView viewHolder.groupPhoto=(NameRoundView)view.findViewById(R.id.frends_phonto);
viewHolder.groupPhoto.setTextName(name);