Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to setShadowLayer when defining shapes in XML in Android?

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>
like image 809
icecream Avatar asked Oct 18 '10 12:10

icecream


1 Answers

Using XML, there's no real way to do this that I know of. I've seen some suggestions of making a second box of the same shape behind the item, and just filling it with black, but I don't feel that's a good solution. I've been trying to find a way to do this myself for a while.

If it helps, here's a link to a similar question I posted, along with some code. I got it working for some images, but it still seems to have trouble finding the alpha channel sometimes. Basically, I've overridden ImageView and put this in the onDraw() method:

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

That was just testing, though, so obviously a lot of the parameters would have to be more generic. I haven't had a lot of time to work on it lately though, but maybe this will help you find your answer.

like image 123
Kevin Coppock Avatar answered Sep 25 '22 20:09

Kevin Coppock