如何在Canvas上绘制要绘制的形状?

时间:2011-11-15 06:32:08

标签: android shape android-canvas

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

我对将形状输出到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>

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

2 个答案:

答案 0 :(得分:6)

让我们调用你的文件'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>

答案 1 :(得分:0)

定义如何?像SVG这样的东西?您需要编写自己的解析器并将形状/ spath转换为对Canvas.drawPath()/Rect()等的调用。您可以编写一个知道如何绘制自己的自定义视图等。无论哪种方式,有人必须编写代码它。膨胀只是解析XML并创建对象图。