自定义组件无法绘制可绘制对象。

3
我想学习创建自定义视图和组件,但遇到了障碍。使用drawable.draw(canvas)方法无法渲染任何绘制对象在画布上,但如果使用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变量包含可绘制的图像。我是通过标准方式获取它的:

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个回答

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);

“这意味着您想要在可绘制对象内绘制您的MyCustomView”- 这是不正确的。 - Mike M.
Drawable#draw() 方法将 Drawable 绘制到传递给它的 Canvas 上。OP 正确地使用了它。 - Mike M.
@MikeM:那为什么它没有被绘制出来呢? - Mehul Joisar
2
你明白了。一个 Drawable 需要边界。++ - Mike M.
1
@MikeM。是的,当我查看谷歌群组上的各种帖子时,我找到了它。 - Mehul Joisar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接