我不明白为什么下面的代码没有把圆准确地放在图像中心

I don't understand why the following code doesn't place the circle exactly in the image center

我不明白为什么下面的代码没有将圆准确地放在图像中心。

let face = collectionView.dequeueReusableCell(withReuseIdentifier: "myFace", for: indexPath) as! Face
print("face cellForItemAt \(indexPath) and frame \(face.frame)")

face.tag = indexPath.row
let _ = face.contentView.subviews.map({[=10=].removeFromSuperview})
let ind = indexPath.row
let vi = UIImageView()
vi.frame = face.contentView.frame
vi.image = UIImage(cgImage: panim[ind])

let layer = CAShapeLayer()
layer.frame = vi.frame
let circle = UIBezierPath(ovalIn: vi.frame)
circle.append(UIBezierPath(rect: vi.frame))
circle.usesEvenOddFillRule = false
layer.path = circle.cgPath
layer.fillColor = UIColor.red.withAlphaComponent(0.0).cgColor
layer.strokeColor = UIColor.yellow.cgColor
layer.fillRule =  kCAFillRuleNonZero
vi.layer.addSublayer(layer)

face.contentView.addSubview(vi)
return face

您将路径偏移两次:一次在路径本身中,一次在形状图层的框架中。你可能两者都不想要。

形状层的路径是相对于形状层的坐标系的,而形状层的框架是相对于其超层(图像视图层)的坐标系的。

对于这两个,您都指定了图像视图的框架,该值与其超级视图有一些偏移;单元格的内容视图。

这对您的代码意味着两件事:

由于shape layer的frame是相对于它的super layer(image view的layer)的,如果你想让shape layer位于image view的左上角,那么你应该设置shape layer的frame到图像视图的边界(或者只是一个原点为零且与图像视图大小相同的矩形)。

layer.frame = vi.bounds

由于形状图层的路径是相对于形状图层的,如果你想绘制一个填充形状图层的圆,那么你的路径应该是形状图层的边界[=26=中的椭圆形].

let circle = UIBezierPath(ovalIn: layer.bounds)