5

If I draw a round rect shape by code I can use setShadowLayer to get a shadow drawn for the shape. Is there an equivalent when defining shapes in XML?

The following example draws a round rect background to a shape. What would I need to add to get a shadow added to the shape? Is it even possible using XML?

shape_test.xml

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#8067BF6A"/>    
    <stroke android:width="3dp" android:color="#80000000" />
    <padding android:left="1dp"
      android:top="1dp"
      android:right="1dp"
      android:bottom="1dp" /> 
    <corners android:bottomRightRadius="7dp"
      android:bottomLeftRadius="7dp"
      android:topLeftRadius="7dp"
      android:topRightRadius="7dp"/> 
</shape>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:padding="10dp"
 android:background="#ffdddddd"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
 <Button android:background="@drawable/shape_test"
 android:padding="5dp"
 android:textStyle="bold"
 android:textSize="28sp"
 android:text="Hello"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />
</LinearLayout>
4

1 回答 1

5

使用 XML,据我所知,没有真正的方法可以做到这一点。我已经看到一些建议在物品后面制作第二个相同形状的盒子,然后用黑色填充它,但我觉得这不是一个好的解决方案。一段时间以来,我一直在尝试自己寻找一种方法来做到这一点。

如果有帮助,这是我发布的类似问题的链接以及一些代码。我让它适用于一些图像,但有时它似乎仍然无法找到 alpha 通道。基本上,我已经覆盖了 ImageView 并将其放入onDraw()方法中:

@Override 
protected void onDraw(Canvas canvas)  
{ 
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.omen); 
    Paint paint = new Paint(); 
    paint.setAntiAlias(true); 
    paint.setShadowLayer(5.5f, 6.0f, 6.0f, Color.BLACK); 
    canvas.drawColor(Color.GRAY); 
    canvas.drawRect(50, 50, 50 + bmp.getWidth(), 50 + bmp.getHeight(), paint); 
    canvas.drawBitmap(bmp, 50, 50, null);        
} 

不过,这只是测试,所以很明显很多参数必须更通用。虽然我最近没有太多时间来研究它,但也许这会帮助你找到答案。

于 2010-10-18T13:15:45.983 回答