今天写了个带边框的圆形头像View,部分代码如下:
//绘制边框
m_Paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2, circle_radius - 1, m_Paint);
//绘制头像
if (id != 0) {
m_Paint.setStyle(Paint.Style.FILL);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), id);
BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
m_Paint.setShader(bitmapShader);
canvas.drawCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2, circle_radius - 2, m_Paint);
}
初次进入没有问题,但是切换页面后再次返回本页,边框线会消失或者看不清楚。
原因是切回本activity后view会重新执行onDraw()方法进行视图的绘制,但是此时的m_Paint已经在第一次加载activity时被设置了渲染器,所以返回本activity后调用的绘制边框的画笔m_Paint是带渲染效果的m_Paint。onDraw()开头加入如下代码后解决:
m_Paint.setShader(null);