【发布时间】: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