【问题标题】:Custom component not drawing drawable自定义组件不可绘制
【发布时间】:2014-12-17 17:51:28
【问题描述】:

我正在尝试学习创建自定义视图和组件,但已经遇到了障碍。我无法使用 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>

如果有人能指出我正确的方向,我将不胜感激。谢谢!

【问题讨论】:

    标签: android


    【解决方案1】:

    你可能错过了界限,试试这样

          //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" - 这是不正确的。
    • Drawable#draw() 方法将 Drawable 绘制到传递给它的 Canvas 上。 OP 使用正确。
    • @MikeM.: 那为什么它没有被平局呢?
    • 你明白了。 Drawable 需要边界。 ++
    • @MikeM。是的,当我查看谷歌群组上的各种帖子时,我可以找到它。
    猜你喜欢
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    相关资源
    最近更新 更多