我想学习创建自定义视图和组件,但遇到了障碍。使用drawable.draw(canvas)方法无法渲染任何绘制对象在画布上,但如果使用canvas.drawBitmap()方法获取位图并绘制,则可以工作。
代码中没有任何花哨的东西:
自定义视图的 xml 代码如下:
代码中没有任何花哨的东西:
@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>
我希望有人能指点我正确的方向。谢谢!
MyCustomView
”- 这是不正确的。 - Mike M.Drawable#draw()
方法将 Drawable 绘制到传递给它的 Canvas 上。OP 正确地使用了它。 - Mike M.