How to draw on top of a layout
I am new to android.
Can anyone help me with this problem.
I have a layout in which I have a imageView. What I want is I want to draw a rectangle on top of this image. The height of the rectangle is obtained during runtime.
I have tried drawing the rectangle by using shapeDrawable class and onDraw() method. But everyti开发者_开发技巧me I draw my layout disappears and what I get is a rectangle in a black background.
Can anyone please help me with this.
You can use a FrameLayout to overlap views. In your layout XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_image"/>
<View
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/my_shape"/>
</FrameLayout>
And then in res/drawable/my_shape.xml
you can have a Shape Drawable, for example:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp"/>
<solid android:color="#00000000"/>
<stroke android:width="3dp" android:color="#ffff0000"/>
</shape>
A second option is to use a custom view instead of the overlay view and override its onDraw
method to do custom Canvas
drawing. In that case you would still use the FrameLayout
to position the view over your ImageView.
A third option is to use a custom view and draw your image into it using drawBitmap
calls in the onDraw
method. This is probably the most flexible of the three methods.
精彩评论