如何快速裁剪圆的外部区域?

问题描述

我使用 UIBezierPath 快速绘制了半圆,父对象是 UIImageView 现在我想剪掉圆的外部区域。我试过 clipsToBounds 但没有用。

enter image description here

   let path = UIBezierPath(arcCenter: CGPoint(x: -60,y: imgView.frame.size.height/2),radius: imgView.frame.size.width*1.3,startAngle: CGFloat(90).toradians(),endAngle: CGFloat(270).toradians(),clockwise: false)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = UIColor.blue.cgColor
    shapeLayer.linewidth = 5
    imgView.clipsToBounds = true
    imgView.layer.addSublayer(shapeLayer)

extension CGFloat {
    func toradians() -> CGFloat {
        return self * .pi / 180
    }
}

EDIT:1 我试过 imgView.layer.mask = shapeLayer 但它消灭了 strokeColor

解决方法

尝试:- imgView.layer.maskstoBounds = true

,

形状图层要么绘制在另一个图层的顶部,要么在将其用作蒙版时剪裁另一个图层。它不能同时进行。

您需要两个形状层。保留您现在拥有的蓝色描边,作为图像视图层的子层。

创建第二个形状图层,在其中安装另一个圆形路径,将其填充颜色设置为任何不透明颜色,然后使用第二个形状图层作为图像视图上的蒙版。您可能需要向遮罩层添加描边颜色和边框宽度,使其足够大,不会遮住蓝色圆圈。 (我忘记了描边是画在其形状边界的内侧、外侧还是居中。我认为它们是居中的,因此除非您还以相同的厚度对遮罩层进行描边,否则它会剪掉蓝色圆圈的外半部分形状层,但我必须尝试确定。)