gpt4 book ai didi

android - 自定义组件不绘制可绘制

转载 作者:太空宇宙 更新时间:2023-11-03 12:18:04 25 4
gpt4 key购买 nike

我正在尝试学习创建自定义 View 和组件,但遇到了障碍。我无法使用 drawable.draw(canvas) 方法在 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);

自定义 View 的 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>

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

最佳答案

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

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

关于android - 自定义组件不绘制可绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27518621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com