裁剪部分区域
利用 mask view 实现,遮罩层实现
裁剪- UIView 实现
// img_w: 原始图片宽度
// img_h: 原始图片高度
let cutView = UIView.init(frame: CGRect.init(x: 0,
y: 0,
width: img_w * 0.5,
height: img_h * 0.5))
// 这里需要有一个颜色,不能为透明
cutView.backgroundColor = .red
imageView.mask = cutView
- CALayer 实现
// img_w: 原始图片宽度
// img_h: 原始图片高度
let cutView = CALayer.init()
cutView.frame = CGRect.init(x: 0,
y: 0,
width: img_w * 0.5,
height: img_h * 0.5)
cutView.backgroundColor = UIColor.red.cgColor
imageView.layer.mask = cutView
镂空部分区域
使用 CAShapeLayer 实现
镂空
let shapeLayer = CAShapeLayer.init()
// maskPath: 为黑色方形蒙版路径
// hollowOutPath: 为黑色蒙版中间镂空的圆形路径
let shapeLayer = CAShapeLayer.init()
let maskPath = UIBezierPath.init(rect: CGRect.init(x: 20, y: 20, width: img_w - 40, height: img_h - 40))
let hollowOutPath = UIBezierPath.init(arcCenter: CGPoint.init(x: img_w * 0.5, y: img_h * 0.5),
radius: img_w * 0.5 * 0.5 * 0.5,
startAngle: 0,
endAngle: 2 * CGFloat(Double.pi),
clockwise: true)
maskPath.append(hollowOutPath)
maskPath.usesEvenOddFillRule = true
shapeLayer.fillRule = .evenOdd
// 蒙版的颜色
shapeLayer.fillColor = UIColor.black.withAlphaComponent(0.6).cgColor
shapeLayer.path = maskPath.cgPath
let maskView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: img_w, height: img_h))
maskView.layer.addSublayer(shapeLayer)
imageView.addSubview(maskView)
网友评论