Created
October 7, 2016 12:15
-
-
Save tartakovsky/7e977e81f1d2827f5fcd5c6c6a3c3d94 to your computer and use it in GitHub Desktop.
UIView+Mask.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Mask UIView with rect/path | |
// inverse = false: part inside rect is kept, everything outside is clipped | |
// inverse = true: part inside rect is cut out, everything else is kept | |
// | |
// Usage: | |
// | |
// // - Cuts rectangle inside view, leaving 20pt borders around | |
// let rect = CGRect(x: 20, y: 20, width: bounds.size.width - 20*2, height: bounds.size.height - 20*2) | |
// targetView.mask(withRect: rect, inverse: true) | |
// | |
extension UIView { | |
func mask(withRect rect: CGRect, inverse: Bool = false) { | |
let path = UIBezierPath(rect: rect) | |
let maskLayer = CAShapeLayer() | |
if inverse { | |
path.appendPath(UIBezierPath(rect: self.bounds)) | |
maskLayer.fillRule = kCAFillRuleEvenOdd | |
} | |
maskLayer.path = path.CGPath | |
self.layer.mask = maskLayer | |
} | |
func mask(withPath path: UIBezierPath, inverse: Bool = false) { | |
let path = path | |
let maskLayer = CAShapeLayer() | |
if inverse { | |
path.appendPath(UIBezierPath(rect: self.bounds)) | |
maskLayer.fillRule = kCAFillRuleEvenOdd | |
} | |
maskLayer.path = path.CGPath | |
self.layer.mask = maskLayer | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Flar How can I mask and use custom area based on user's gesture.Actually I want to crop the portion of the picture based on user's selection like if he wants to crop his body in an image leaving the background then he could do so.How can I do that?