自定义联系人头像显示第一个字符

 

/**

 * @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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值