几点观察:
您只是在查看路径的视觉表示,而不是视图。要查看视图,您应该设置liveView
:PlaygroundPage
import PlaygroundSupport
和
PlaygroundPage.current.liveView = myView
PlaygroundPage.current.needsIndefiniteExecution = true
顺便说一句,您的圆形视图从 0 逆时针变为 π。即,这是一个圆圈的上半部分。因此,如果圆的中心有一个y
of 0
,这意味着您的路径在视图上方并且不与它重叠。将其设置为顺时针方向(以获得圆的下半部分)或y
向下移动(使圆的上半部分与视图重叠)。
我发现游乐场会调整它们的大小liveView
(即使我设置wantsFullScreenLiveView
为false
),所以如果我想要特定大小的视图,我会使用“容器视图”。即,我将添加myView
为 的子视图containerView
,添加约束以将其放在该容器的中心,然后设置containerView
为liveView
.
仅相切相关,但您将蒙版形状图层的颜色设置为橙色。蒙版只使用它们的 alpha 通道,所以使用橙色是没有意义的。我们通常将遮罩设置为白色,但我只是想确保我们没有将遮罩的颜色与遮罩视图的颜色混为一谈。
因此,将所有这些放在一起:
import UIKit
import PlaygroundSupport
// create container
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
// create view that we'll mask with shape layer
let rect = CGRect(x: 0, y: 0, width: 200, height: 200)
let myView = UIView()
myView.translatesAutoresizingMaskIntoConstraints = false
myView.backgroundColor = .orange
myView.clipsToBounds = true
containerView.addSubview(myView)
// create mask
let circlePath = UIBezierPath(arcCenter: CGPoint(x: rect.midX, y: rect.minY), radius: rect.height, startAngle: 0, endAngle: .pi, clockwise: true)
let circleShape = CAShapeLayer()
circleShape.masksToBounds = false
circleShape.path = circlePath.cgPath
circleShape.fillColor = UIColor.white.cgColor
circleShape.strokeColor = UIColor.white.cgColor
myView.layer.mask = circleShape
// center masked view in container
NSLayoutConstraint.activate([
myView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
myView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
myView.widthAnchor.constraint(equalToConstant: 200),
myView.heightAnchor.constraint(equalToConstant: 200)
])
// show it
PlaygroundPage.current.liveView = containerView
PlaygroundPage.current.needsIndefiniteExecution = true
这会产生:
因此,通过使弧顺时针方向移动并使用liveView
,我们现在可以看到它。显然,圆心为midX, minY
且半径为 的圆弧height
不能显示完整的半圆。如果您想看到完整的半圆,则必须将半径设置为width / 2
(或增加width
of或其他)。rect