Creating a shadow around a canvas drawn shape?

mgibson picture mgibson · Aug 7, 2013 · Viewed 25k times · Source

What steps are required to create a shape e.g. rectangle with a shadow from scratch using a Canvas?

Adding a shadow layer to the paint used to draw the rectangle yielded no success.

Answer

mgibson picture mgibson · Aug 7, 2013

No need for a Bitmap, just needed to set the layer type to LAYER_TYPE_SOFTWARE the original approach worked.

public class TestShapeShadow extends View
{
    Paint paint;

    public TestShapeShadow(Context context)
    {
       super(context);  

        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setShadowLayer(12, 0, 0, Color.YELLOW);

        // Important for certain APIs 
        setLayerType(LAYER_TYPE_SOFTWARE, paint);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {   
        canvas.drawRect(20, 20, 100, 100, paint);
    }
}