今天寫了個帶邊框的圓形頭像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);