3

这是我的代码的简化版本:

Paint p = new Paint();

p.setShader(borderShader); //use a bitmap as a texture to paint with
p.setFilterBitmap(true);
p.setShadowLayer(20, 20, 20, Color.BLACK);

canvas.clipRect(10,0,width-10,height);
canvas.drawCircle(width/2,height/2,1000/2,p);

所以图像看起来像这样:

在此处输入图像描述

两边都夹住的圆圈。

问题是,因为阴影向下偏移了 20 个像素,向右偏移了 20 个像素。阴影的右侧部分被 clipRect 剪裁,不会显示。

我必须使用 clipRect 而不是简单地绘制一个白色矩形来裁剪圆圈,因为圆圈的左右两侧需要透明才能在下面显示背景。

4

1 回答 1

2

我最终使用 Path 通过使用两条弧线和两条线段来绘制形状,而不是在圆上使用矩形剪切区域。

后来进行了大量的三角函数和数学运算,它完美地工作。

编辑:

根据请求,这是我最终使用的代码示例。请注意,这是为我的应用程序量身定制的,并且可以绘制出与我的问题完全相同的形状。

private void setupBorderShadow()
{
    //Set up variables
    int h = SUI.WIDTH / 2; // x component of the center of the circle 
    int k = SUI.HEIGHT_CENTER; // y component of the center of the circle

    int x = SUI.WIDTH / 2 - 4 * SUI.CIRCLE_RADIUS_DIFFERENCE - SUI.BORDER_WIDTH; //left side of the rectangle
    int r = 6 * SUI.CIRCLE_RADIUS_DIFFERENCE + SUI.BORDER_WIDTH; //radius of circle


    //define a rectangle that circumscribes the circle
    RectF circle = new RectF(h - r, k - r, h + r, k + r);

    Path p = new Path();
    //draw a line that goes from the bottom left to the top left of the shape
    p.moveTo(x, (float) (k + Math.sqrt(-(h * h) + 2 * h * x + r * r - (x * x))));
    p.lineTo(x, (float) (k - Math.sqrt(-(h * h) + 2 * h * x + r * r - (x * x))));

    //calculate the angle that the top left of the shape represents in the circle
    float angle = (float) Math.toDegrees(Math.atan(Math.sqrt(-(h * h) + 2 * h * x + r * r
            - (x * x))
            / (h - x)));

    //draw an arc from the top left of shape to top right of shape 
    p.arcTo(circle, 180 + angle, (180 - angle * 2));

    // the x component of the right side of the shape
    x = SUI.WIDTH / 2 + 4 * SUI.CIRCLE_RADIUS_DIFFERENCE + SUI.BORDER_WIDTH;

    //draw line from top right to bottom right
    p.lineTo(x, (float) (k + Math.sqrt(-(h * h) + 2 * h * x + r * r - (x * x))));

    //draw arc back from bottom right to bottom left. 
    p.arcTo(circle, angle, (180 - angle * 2));


    //draw the path onto the canvas
    _borderCanvas.drawPath(p, SUI.borderShadowPaint);
}

请注意,我使用的某些变量(例如“CIRCLE_RADIUS_DIFFERENCE”)可能没有意义。忽略这些,它们是应用程序特定的常量。在几何计算中实际产生影响的所有变量都被标记。

于 2012-11-23T03:41:45.867 回答