首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在不裁剪阴影的情况下裁剪canvas.drawCircle()?

如何在不裁剪阴影的情况下裁剪canvas.drawCircle()?
EN

Stack Overflow用户
提问于 2012-11-20 12:53:23
回答 1查看 2.3K关注 0票数 3

下面是我的代码的简化版本:

代码语言:javascript
复制
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,而不是简单地绘制一个白色矩形来裁剪圆,因为圆的左右两边需要是透明的,才能显示下面的背景。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-23 11:41:46

我最终使用Path来绘制形状,使用两个圆弧和两个线段,而不是使用圆形上的矩形裁剪区域。

经过大量的三角运算和数学运算后,它就完美地工作了。

编辑:

对于每个请求,下面是我最终使用的代码示例。请注意,这是为我的应用程序定制的,并将绘制出与我问题中的形状完全相同的形状。

代码语言:javascript
复制
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“,可能没有意义。忽略这些,它们是应用程序特定的常量。所有在几何计算中实际起作用的变量都会被标记。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13466797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档