Creating a shadow around a canvas drawn shape?

前端 未结 3 829
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 17:44

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

3条回答
  •  深忆病人
    2021-02-01 18:11

    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/

    public class MyViewWithShadow extends View {
    
        Paint paint;
        int mainColor;
        int shadowColor;
    
        // shadow properties
        int offsetX = -25;
        int offsetY = 30;
        int blurRadius = 5;
    
        public MyViewWithShadow(Context context)
        {
            super(context);
    
            mainColor = Color.RED;
            shadowColor = Color.BLACK; // this color can also have alpha
    
            paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setStyle(Paint.Style.FILL);
        }
    
        @Override
        protected void onDraw(Canvas canvas)
        {   
            // Create paint for shadow
            paint.setColor(shadowColor);
            paint.setMaskFilter(new BlurMaskFilter(
                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);
        }
    }
    

提交回复
热议问题