如何只剪切视图的左侧和右侧?

时间:2018-11-29 02:48:26

标签: swift clip

我只想在视图上裁剪子视图的左侧和右侧。 因此,在超级视图的顶部和底部都有子视图的内容。 我该怎么办?

1 个答案:

答案 0 :(得分:1)

设置父视图主层的mask属性:

// The mask has the same width as parentView but much taller. It is not visible
// by itself so so can set `dy` to any value. Negative values for `dy` means
// making it grow in height
let maskRect = parentView.bounds.insetBy(dx: 0, dy: -1000)

let maskPath = UIBezierPath(rect: maskRect)
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.cgPath

// The color is not important here, its opacity matters more. Opaque or
// partially-opaque pixels in the mask will allow subviews to show through.
// Fully transparent pixels will hide it. Kinda backwards if you ask me
maskLayer.fillColor = UIColor.black.cgColor
parentView.layer.mask = maskLayer

这里有几个插图。 parentView是黑色线框。

没有面具:

No mask

带遮罩(仅在左侧和右侧剪裁):

With mask - clipping on left and right