- 声明style
- onMeasure
- onSizeChanged
- onDraw
- 资源回收
style
<declare-styleable name="RoundCornerImageView">
<attr name="radius" format="dimension" /> // 圆角半径
<attr name="hoverColor" format="color" /> // 圆角颜色
</declare-styleable>
onSizeChanged
mBoundedRectF.set(0,0, w, h); //矩形宽高
onDraw
canvas.saveLaver会返回给一个新的Layer, 基于几个透明的Bitmap绘制,当restoreToCount时会将Layer出栈并最终和栈顶结合在一起,此处不适用clipPath(锯齿问题),使用xfmode.
- 通过Path绘制带圆角的矩形.
- 通过XfMode的SRC_IN效果设置.
- 如果不是BitmapDrawable则绘制圆角矩形即可.
- XfMode效果图 http://ssp.impulsetrain.com/porterduff.html
Drawable drawable = getDrawable();
if (drawable instanceof BitmapDrawable) {
Paint paint = ((BitmapDrawable)drawable).getPaint();
setLayerType(View.LAYER_TYPE_HARDWARE, paint);
Rect bitmapBounds = drawable.getBounds();
mDrawableRect.set(bitmapBounds);
int saveCount = canvas.saveLayer(mDrawableRect, null, Canvas.ALL_SAVE_FLAG);
getImageMatrix().mapRect(mDrawableRect);
paint.setAntiAlias(true);
paint.setColor(mHoverColor);
mPath.reset();
mPath.addRoundRect(mBoundedRectF, cornerRadius, cornerRadius, Path.Direction.CW);
canvas.drawPath(mPath, paint);
Xfermode oldMode = paint.getXfermode();
paint.setXfermode(mXfermode);
super.onDraw(canvas);
paint.setXfermode(oldMode);
canvas.restoreToCount(saveCount);
} else {
mPath.reset();
mPath.addRoundRect(mBoundedRectF, cornerRadius, cornerRadius, Path.Direction.CW);
mColorPaint.setColor(mHoverColor);
canvas.drawPath(mPath, mColorPaint);
}
资源回收
// 记录resID,回收资源
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
recycleBitmap();
once = false;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!once) {
setRoundCornerDrawable(resID);
}
}
private void recycleBitmap() {
Drawable drawable = getDrawable();
if (drawable instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
bitmap.recycle(); // c
System.gc(); // java
}
}