Daniel Chepenko
Daniel Chepenko

Reputation: 2268

Create mask layer for UIView using CAShapeLayer()

I have to create a mask layout for my view, but I can't get the result I want to obtain

@IBOutlet weak var viewToCrop: UIView!
let angle = CGFloat(2*M_PI/3)

func createMask() {
    let mask = CAShapeLayer()
    mask.frame = viewToCrop.layer.bounds
    let heightButton = viewToCrop.frame.height
    let lineWidth = -heightButton/tan(angle)

    let width = viewToCrop.layer.frame.size.width
    let height = viewToCrop.layer.frame.size.height

    let path = CGPathCreateMutable()
    CGPathMoveToPoint(path, nil, 0, 0)
    CGPathAddLineToPoint(path, nil, width, 0)
    CGPathMoveToPoint(path, nil, width - lineWidth, height)
    CGPathAddLineToPoint(path, nil, lineWidth, height)
    CGPathAddLineToPoint(path, nil, 0, 0)

    mask.path = path
    viewToCrop.layer.mask = mask
}

I need to create such figure:

enter image description here

However after running me code I get the rectangular. What am I doing wrong?

P.S. I'm working on a legacy project on Swift 2

Upvotes: 0

Views: 813

Answers (1)

agibson007
agibson007

Reputation: 4373

I don't have a Swift 2 compiler option but I am going to take a stab and hopefully get you close. The biggest thing I think is the Path lineWidth needed to be divided by 2 for the coordinates. Another thing to note is that if the height of the view is too great then 60 is too steep. I would suggest drawing it based on a percentage unless you need the exact angle. Did my best without a Swift 2 compiler so let me know.

@IBOutlet weak var viewToCrop: UIView!
let angle = CGFloat(2*M_PI/3)

func createMask() {
     let mask = CAShapeLayer()
     mask.frame = viewToCrop.layer.bounds
     let heightButton = viewToCrop.frame.width
     let lineWidth = -heightButton/tan(angle)

     let width = viewToCrop.layer.frame.size.width
     let height = viewToCrop.layer.frame.size.height

     let path = CGPathCreateMutable()
     CGPathMoveToPoint(path, nil, 0, 0)
     CGPathAddLineToPoint(path, nil, width, 0)
     CGPathMoveToPoint(path, nil, width - lineWidth/2, height)
     CGPathAddLineToPoint(path, nil, lineWidth/2, height)
     CGPathAddLineToPoint(path, nil, 0, 0)

     mask.path = path
     viewToCrop.layer.mask = mask
  }

Result Result

Upvotes: 1

Related Questions