gpt4 book ai didi

android - 如何膨胀形状以在 Canvas 上绘制?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:33:58 32 4
gpt4 key购买 nike

我的可绘制对象目录中的 xml 文件中存储了一个形状。我想在我的 Canvas 中使用它(我知道我可以在代码中定义形状,但我试图弄清楚如何以更“Android”的方式实现它)。

对于将形状输出到 Canvas 的语法,我一头雾水。我应该尝试将其转换为 Shape 还是 Drawable?它需要矩阵吗?油漆?等

我不需要太多细节,只需指出正确的方向:)

谢谢。

[编辑]我的 Android XML 形状如下所示:

    <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke android:width="3px" android:color="#583010"/>
<solid android:color="#ffffff" />
<corners android:bottomRightRadius="3px" android:bottomLeftRadius="3px"
android:topLeftRadius="3px" android:topRightRadius="3px"/>
</shape>

我假设一定有某种方法可以让它膨胀,不是吗?[/编辑]

最佳答案

我们将您的文件命名为“res/drawable/my_shape.xml”。以下代码行将从 XML 扩展 my_shape.xml 并将其内容绘制到 Canvas 上。 ImageView 用于证明这是可行的。

Drawable shape = getResources().getDrawable(R.drawable.my_shape);
Bitmap bitmap = Bitmap.createBitmap( shape.getIntrinsicWidth(), shape.getIntrinsicHeight(), Config.ARGB_8888 );
Canvas canvas = new Canvas( bitmap );
shape.setBounds( 0, 0, canvas.getWidth(), canvas.getHeight() );
shape.draw( canvas );

ImageView imageView = (ImageView) findViewById(R.id.my_imageView);
imageView.setImageBitmap( bitmap );

确保这些代码行在 onCreate 中的 setContentView 之后执行。

为了尽可能消除混淆,这是 my_shape.xml 的功能示例:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="ring"
android:thicknessRatio="1.9"
android:useLevel="false" >

<solid android:color="#DDAAAFFF" />

<size
android:height="10dp"
android:width="10dp" />

<stroke
android:width="1dp"
android:color="#AAAAAA" />

</shape>

关于android - 如何膨胀形状以在 Canvas 上绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8132367/

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