【问题标题】:How to clip a canvas.drawCircle() without clipping the shadow?如何在不裁剪阴影的情况下裁剪 canvas.drawCircle()?
【发布时间】:2012-11-08 03:24:33
【问题描述】:

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

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而不是简单地绘制一个白色矩形来剪切圆,因为圆的左右需要透明才能在下面显示背景。

【问题讨论】:

  • 您必须在应用阴影之前对其进行剪辑。我没有尝试过,但在调用 setShadowLayer() 之前尝试调用 clipRect。
  • 我尝试在clipRect之后调用setShadowLayer,但不幸的是没有成功。
  • 好的,值得一试。有了阴影和透明背景,也许 9-patch 是最好的方法?
  • 嗯,这是一种可能的方法。我会考虑的,谢谢!
  • 我也在想也许不是把它画成一个裁剪圆,我可以用 2 条弧线和 2 条线段制作一条路径并填充它。将调查

标签: android graphics clipping


【解决方案1】:

我最终使用 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”)可能没有意义。忽略这些,它们是应用程序特定的常量。对几何计算中实际产生影响的所有变量都进行了标记。

【讨论】:

  • 为什么不发布“大量的三角和数学”,也许可以节省其他人的时间?
  • 好的,会的。我最初决定反对它,因为我认为该解决方案可能过于针对我自己的问题量身定制(因为所有计算主要是为了创建我的应用程序需要的特定形状)。虽然我猜它们可能对人们有所帮助。
猜你喜欢
  • 2013-07-12
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
  • 2014-07-25
相关资源
最近更新 更多