自定义组件不绘制可绘制

时间:2014-12-17 05:00:12

标签: android

我试图学习创建自定义视图和组件,并且已经遇到了障碍。我无法使用drawable.draw(canvas)方法在canvas上绘制任何drawable。但是如果我得到位图并使用canvas.drawBitmap()方法绘制它,它就可以工作。

代码中没有任何花哨的东西:

@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();
    }
}

日志显示mThumb变量包含drawable。我以标准的方式获得它:

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是:

<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" />

在attrs.xml中:

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

如果有人能指出我正确的方向,我真的很感激。谢谢!

1 个答案:

答案 0 :(得分:7)

你可能会错过界限,试试这个

      //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);
相关问题