美文网首页
Android 圆角View

Android 圆角View

作者: 钰大人 | 来源:发表于2018-12-26 18:26 被阅读0次
  • 声明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.

        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
        }
    }

相关文章

网友评论

      本文标题:Android 圆角View

      本文链接:https://www.haomeiwen.com/subject/zbkklqtx.html