简体   繁体   中英

How do I inflate a shape to draw on a Canvas?

I have a shape stored in an xml file in my drawables directory. I'd like to use it in my Canvas (I know I can define the shape in code, but I'm trying to figure out how to implement it the more "Androidy" way).

I'm at a loss as to the syntax for getting the shape out to the Canvas. Should I be trying to transform it into a Shape or a Drawable? Does it need a Matrix? A Paint? etc.

I don't need a lot of details, just point me in the right direction :)

Thanks.

[edit] my Android XML shape looks like this:

    <?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>

I'm assuming there must be some way to get that inflated, no? [/edit]

Let's call your file 'res/drawable/my_shape.xml'. The following lines of code will inflate my_shape.xml from XML and draw its contents onto a Canvas. The ImageView is used to prove that this works.

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

Make sure these lines of code are executed after setContentView in your onCreate.

To eliminate as much confusion as possible, this is a functional sample of 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>

Defined how? Something like SVG? You'll need to write your own parser and translate shape/spaths to calls to Canvas.drawPath()/Rect() , etc. You can write a custom view that knows how to draw itself, etc. Either way, someone has to write the code for it. Inflating is just parsing XML and creating an object graph.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM