Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom View not drawing itself

I read different questions here about this topic, but I still can't find an answer. Feel free to close this question for any reason.

I have a simple Circle class that extends View.

The code for this class is:

public class ProgressCircle extends View {
    Paint mCirclePaint;
    float extRadius;
    float viewWidth, viewHeight;
    float centerX, centerY;

    public ProgressCircle(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
        init();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        float xpad = (float) getPaddingLeft() + getPaddingRight();
        float ypad = (float) getPaddingTop() + getPaddingBottom();
        float ww = (float)w - xpad; float hh = (float)h - ypad;
        extRadius = Math.min(ww, hh) / 2;

        viewWidth = this.getWidth();
        viewHeight = this.getHeight();
        centerX = viewWidth / 2; centerY = viewHeight / 2;

        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(centerX, centerY, extRadius, mCirclePaint);
        canvas.drawText("ciao", 0, 0, mCirclePaint);    
    }

    private void init() {
        mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint.setColor(0x666666);
        mCirclePaint.setStyle(Paint.Style.FILL_AND_STROKE);
    }

I confirmed that every method in this classed is called when the main activity is created (through the use of some Log.d()s). I added a <com.mypackage.Circle> element in my main activity's LinearLayout and after that I added a sample testing button.

What I achieved is that the button is shown while my Circle isn't, but still the button (which in the LinearLayout comes after the Circle) is not the first element of the layout: that makes me think that something actually happens, but nothing gets drawn.

like image 819
whatyouhide Avatar asked Oct 04 '22 22:10

whatyouhide


1 Answers

It was just a silly problem: the color in mCirclePaint.setColor(0x666666) was an invalid one. It worked with mCirclePaint.setColor(Color.RED) or with any other color defined in the res folder.

If you need to specify a color value, you'll have to include the transparency byte (otherwise it is not a 32bit integer that you are specifying, but a 24bit). So 0x666666 is invalid, but 0xff666666 is a valid color and will draw.

like image 62
whatyouhide Avatar answered Oct 10 '22 02:10

whatyouhide