Search code examples
javaandroidcanvasondraw

Android custom view canvas clear fails


I'm writing a simple custom View that should draw the an RSSI signal shape (two overlapping triangles one filled proportionally with the level of the signal). The components works except for the clearing of canvas.

I tought I need to do something like that:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    final int mWidth = getMeasuredWidth();
    final int mHeight = getMeasuredHeight();
    final float _fillw = mWidth * (mLevel) / 100f;
    final float _fillh = mHeight * (100f - mLevel) / 100f;

    //canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
    canvas.drawColor(Color.BLACK);

    if (mLevel < mWarnLevel)
        mFillPaint.setColor(mWarnFillColor);
    else if ((mLevel >= mWarnLevel) && (mLevel < mSafeLevel))
        mFillPaint.setColor(mFillColor);
    else if (mLevel >= mSafeLevel)
        mFillPaint.setColor(mSafeFillColor);

    mFramePath.moveTo(0, mHeight);
    mFramePath.lineTo(mWidth, mHeight);
    mFramePath.lineTo(mWidth, 0);
    mFramePath.close();

    mFillPath.moveTo(0, mHeight);
    mFillPath.lineTo(_fillw, mHeight);
    mFillPath.lineTo(_fillw, _fillh);
    mFillPath.close();

    canvas.drawPath(mFramePath, mFramePaint);
    canvas.drawPath(mFillPath, mFillPaint);
}

public void setLevel(int level) {
    if (this.mLevel != level) {
        this.mLevel = level;
        invalidate();
    }
}

The level is drawn correctly until it grows and the triangle area also get larger. When it start to decrease the area is not updated anymore probably beacuse the background is not cleared. I tried also to use the commented .drawColor() line without luck.

P.S. I need to have a transparent background on this View.


Solution

  • You just have to clear the path

    public void clear()
    {
     mFramePath.reset();
     mFillPath.reset();
     invalidate();
    }