Skip to content Skip to sidebar Skip to footer

Creating A Shadow Around A Canvas Drawn Shape?

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

Solution 1:

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

publicclassTestShapeShadowextendsView
{
    Paint paint;

    publicTestShapeShadow(Context context)
    {
       super(context);  

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

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

    @OverrideprotectedvoidonDraw(Canvas canvas)
    {   
        canvas.drawRect(20, 20, 100, 100, paint);
    }
}

Solution 2:

  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

Solution 3:

I followed the ideas of @pskink above and found a solution. I put the code snippet here for anyone in need.

If you wonder what shadow properties are, you can refer to this tester: https://okawa-h.github.io/box-shadow_tester/

publicclassMyViewWithShadowextendsView {

    Paint paint;
    int mainColor;
    int shadowColor;

    // shadow propertiesintoffsetX= -25;
    intoffsetY=30;
    intblurRadius=5;

    publicMyViewWithShadow(Context context)
    {
        super(context);

        mainColor = Color.RED;
        shadowColor = Color.BLACK; // this color can also have alpha

        paint = newPaint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.FILL);
    }

    @OverrideprotectedvoidonDraw(Canvas canvas)
    {   
        // Create paint for shadow
        paint.setColor(shadowColor);
        paint.setMaskFilter(newBlurMaskFilter(
            blurRadius /* shadowRadius */,
            BlurMaskFilter.Blur.NORMAL));

        // Draw shadow before drawing object
        canvas.drawRect(20 + offsetX, 20 + offsetY, 100 + offsetX, 100 + offsetY, paint);

        // Create paint for main object
        paint.setColor(mainColor);
        paint.setMaskFilter(null);

        // Draw main object 
        canvas.drawRect(20, 20, 100, 100, paint);
    }
}

Post a Comment for "Creating A Shadow Around A Canvas Drawn Shape?"