答案 0 :(得分:4)
以下是一个简单的实现,您可以使用CAShapeLayer获得类似的效果。
现在,如果你看一下上面的图像,矩形的大小与你的imageView相同。如果您以某种方式设法移除未交叉的形状部分,您将获得所需的效果。
这将是您将要屏蔽的图像部分,
使用CAShapeLayer可以很容易地实现这一点。
这是一个可以使用的简单实现,
let image = UIImage(named: "image.jpg")
let imageSize = image!.size
let imageView = UIImageView(frame: CGRect(origin: CGPoint.zero, size: imageSize))
imageView.clipsToBounds = true
imageView.image = image
let curveRadius: CGFloat = imageSize.width * 0.005
let invertedRadius: CGFloat = 1.0 / curveRadius
// draw ellipse in rect with big width, but same height
let ellipticalPath = UIBezierPath(ovalInRect: CGRectMake(0, 0, imageSize.width + 2 * invertedRadius * imageSize.width, imageSize.height))
// transform it to center of imageView
ellipticalPath.applyTransform(CGAffineTransformMakeTranslation(-imageSize.width * invertedRadius, 0))
// create rectangle path exactly similar to imageView
let rectanglePath = UIBezierPath(rect: imageView.bounds)
// translate it by 0.5 ratio in order to create intersection between circle and rectangle
rectanglePath.applyTransform(CGAffineTransformMakeTranslation(0, -imageSize.height * CGFloat(0.5)))
// append rectangle to elliptical path
ellipticalPath.appendPath(rectanglePath)
// create mask
let maskLayer = CAShapeLayer()
maskLayer.frame = imageView.bounds
maskLayer.path = ellipticalPath.CGPath
imageView.layer.mask = maskLayer
以下是它的外观,
您可以根据需要调整 curveRadius 的值。
注意:由于CAShapeLayer上的fillRule属性,其形状图层交叉是可能的,其默认值为kCAFillRuleNonZero。点击此处了解详情,https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CAShapeLayer_class/#//apple_ref/occ/instp/CAShapeLayer/fillRule