25

使用 Canvas 从头开始​​创建带有阴影的形状(例如矩形)需要哪些步骤?

向用于绘制矩形的颜料添加阴影层没有成功。

4

3 回答 3

53

不需要位图,只需将图层类型设置LAYER_TYPE_SOFTWARE为原始方法即可。

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);
    }
}
于 2013-08-07T11:09:51.890 回答
9

我按照上面@pskink 的想法,找到了解决方案。我把代码片段放在这里供有需要的人使用。

如果你想知道阴影属性是什么,可以参考这个测试器: 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);
    }
}
于 2020-05-19T01:56:00.890 回答
8
  1. 创造。一个路径,添加一些元素到它

  2. 将 BlurMaskFilter 设置为 Paint

  3. 用 dx, dy 阴影偏移绘制路径

  4. 未设置掩码过滤器

  5. 没有再画一条路。抵消

于 2013-08-07T09:33:23.553 回答