Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom component not drawing drawable

Tags:

android

I'm trying to learn to create custom views and components, and have already hit a road block. I cannot get any drawable to render on canvas using the drawable.draw(canvas) method. But it works if I get the bitmap and draw it using canvas.drawBitmap() method.

There isn't anything fancy in the code either:

@Override
protected void onDraw(Canvas canvas) {

    // drawing bitmap directly works
    /*
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    canvas.drawBitmap(bitmap, 10, 10, paint);
    */

    // this doesn't work but mThumb is not null in log
    if(mThumb != null) {
        canvas.save();
        mThumb.draw(canvas);
        Log.d("Custom component - ", "mThumb : " + mThumb);
        canvas.restore();
    }
}

The log shows the mThumb variable contains the drawable. I'm getting it the standard way:

if(attrs != null) {
    final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
    color = a.getColor(R.styleable.CustomView_cv_color, color);
    thumb = a.getDrawable(R.styleable.CustomView_cv_thumb);
    setThumb(thumb);
    a.recycle();
}

setColor(color);

The xml for the custom view is:

<me.mycustomview.MyCustomView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:cv_color="@android:color/holo_red_light"
    app:cv_thumb="@drawable/ic_launcher" />

And in attrs.xml:

<declare-styleable name="CustomView">
    <attr name="cv_color" format="color" />
    <attr name="cv_thumb" format="reference" />
</declare-styleable>

I'd really appreciate it if someone could point me in the right direction. Thanks!

like image 666
Raghuveer Avatar asked Nov 21 '25 00:11

Raghuveer


1 Answers

You might be missing the bounds, try like this

      //try setting bounds before you draw so that OS can know the area in which you want to draw.you may also pass some Rect object while setting up bounds
      mThumb.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
      mThumb.draw(canvas);
like image 181
Mehul Joisar Avatar answered Nov 23 '25 13:11

Mehul Joisar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!