2011-03-10 67 views
2

我是android新手。如何在布局顶部绘制

任何人都可以帮助我解决这个问题。

我有一个我有一个imageView的布局。我想要的是我想在这张图片上画一个矩形。矩形的高度在运行时获得。

我已经尝试使用shapeDrawable类和onDraw()方法绘制矩形。但每次我画布局消失,我得到的是一个黑色背景中的矩形。

任何人都可以帮助我这个。

+0

请过帐一些代码。 – 2011-03-10 16:18:37

回答

7

您可以使用FrameLayout来重叠视图。在您的布局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> 

然后在res/drawable/my_shape.xml你可以有一个Shape Drawable,例如:

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

的第二个选择是使用,而不是重叠视图自定义视图并覆盖其onDraw方法来自定义Canvas绘图。在这种情况下,您仍然会使用FrameLayout将视图定位在ImageView上。

第三种选择是使用自定义视图并使用onDraw方法中的drawBitmap调用将图像绘制到其中。这可能是三种方法中最灵活的。