A custom non-drawable component

I am trying to learn how to create custom views and components and have already hit the roadblock. I can't seem to get the ability to draw to the canvas using the drawable.draw (canvas) method. But it works if I get a bitmap and draw it using the canvas.drawBitmap () method.

There is nothing interesting in the code:

@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 displays the mThumb variable containing the drawable. I get it in 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);

      

xml for custom view:

<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 would really appreciate it if someone could point me in the right direction. Thank!

+3


source to share


1 answer


You may be missing borders, try 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);

      

+6


source







All Articles