Created
April 15, 2019 20:06
-
-
Save ahmedAlmasri/8d5038f2fda0db0d5a67a94fb8c81d71 to your computer and use it in GitHub Desktop.
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
func getPathPayer(arrPathPoints:[CGPoint]) throws -> CAShapeLayer { | |
enum PathError : Error{ | |
case moreThan2PointsNeeded | |
} | |
guard arrPathPoints.count > 2 else { | |
throw PathError.moreThan2PointsNeeded | |
} | |
let lineColor = UIColor.blue | |
let lineWidth: CGFloat = 2 | |
let path = UIBezierPath() | |
let pathLayer = CAShapeLayer() | |
for (index,pathPoint) in arrPathPoints.enumerated() { | |
switch index { | |
//First point | |
case 0: | |
path.move(to: pathPoint) | |
//Last point | |
case arrPathPoints.count - 1: | |
path.addLine(to: pathPoint) | |
path.close() | |
//Middle Points | |
default: | |
path.addLine(to: pathPoint) | |
} | |
} | |
pathLayer.path = path.cgPath | |
pathLayer.strokeColor = lineColor.cgColor | |
pathLayer.lineWidth = lineWidth | |
pathLayer.fillColor = UIColor.red.cgColor | |
return pathLayer | |
} | |
// Using | |
do { | |
let rectangleLayer = try getPathPayer(arrPathPoints: [ | |
CGPoint(x: 110, y: 110), //Top-Left | |
CGPoint(x: 170, y: 110), //Top-Right | |
CGPoint(x: 130, y: 130), //Bottom-Right | |
CGPoint(x: 110, y: 130)]) //Bottom-Left | |
// let view = UIView(frame: CGRect(x: 0, y: 0, width: 375, height: 200)) | |
view.layer.addSublayer(rectangleLayer) | |
print( view) | |
} catch { | |
debugPrint(error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment