android – Creating a shadow around a canvas drawn shape?-ThrowExceptions

Exception or error:

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.

How to solve:

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

###

  1. create. a Path, add some elements to it

  2. set BlurMaskFilter to a Paint

  3. draw a path with dx, dy shadow offset

  4. unset mask filter

  5. draw a path again with no. offset

Leave a Reply

Your email address will not be published. Required fields are marked *