I have a mask applied to a view using CAShapeLayer
and UIBezierPath
. I’d like to add a rounding effect to the line joins but it’s not working. How do I round the corners of this shape?
You can plug the following into an Xcode playground.
import PlaygroundSupport
import UIKit
private class ProfileImageView: UIView {
private let imageView = UIImageView()
var image: UIImage?
override init(frame: CGRect) {
super.init(frame: frame)
imageView.clipsToBounds = true
imageView.backgroundColor = UIColor.black
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
addSubview(imageView)
imageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
imageView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
imageView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
required init?(coder: NSCoder) {
return nil
}
override func draw(_ rect: CGRect) {
let h = rect.height
let w = rect.width
let path = UIBezierPath()
let shapeLayer = CAShapeLayer()
path.move(to: .zero)
path.addLine(to: CGPoint(x: w-32, y: 0))
path.addLine(to: CGPoint(x: w, y: 32))
path.addLine(to: CGPoint(x: w, y: h))
path.addLine(to: CGPoint(x: 32, y: h))
path.addLine(to: CGPoint(x: 0, y: h-32))
path.close()
path.lineJoinStyle = .round
shapeLayer.lineJoin = .round
shapeLayer.path = path.cgPath
layer.mask = shapeLayer
imageView.image = image
}
}
class VC: UIViewController {
override func loadView() {
view = UIView()
view.backgroundColor = .gray
let imgView = ProfileImageView()
imgView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(imgView)
imgView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imgView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
imgView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -64).isActive = true
imgView.heightAnchor.constraint(equalTo: view.widthAnchor, constant: -64).isActive = true
}
}
PlaygroundPage.current.liveView = VC()
2
Answers
lineJoinStyle
is only for stroked paths. Since yours is a mask, you need a filled path instead so I think you’ll need to usepath.addCurve
to achieve rounded corners in your mask. Or depending on your shape and size you may be able to just applylineWidth
,strokeColor
andlineJoinStyle
to yourCAShapeLayer
and get the rounded effect you’re looking for.Still trying to guess at your goal, but maybe this is what you’re looking for?