1

I created a CAShapeLayer and added it as a sublayer instead of working directly on view.layer to allow a dotted or dashed border (using lineDashPattern). The issue is that at some border widths and with some corner radius values - random vertical lines begin appearing. Zoom in (if you have to) on the picture, on the right-hand side.

Note: the lines are vertical on my physical test device but horizontal in simulator.

Click to see screenshot of test project

I've created a small test project to demonstrate this. In storyboard I setup the red square and slider and all the border work is done at the bottom of this code snippet (I've included everything in the class for clarity):

@IBOutlet weak var testView: UIView!

@IBOutlet weak var slider: UISlider!

var border : CAShapeLayer?

override func viewDidLoad() {
    super.viewDidLoad()

    updateViewCornerRadius(newCornerRadius: 0.0)

    slider.addTarget(self, action: #selector(ViewController.onSliderChange), for: UIControlEvents.valueChanged)
}

func onSliderChange() {
    updateViewCornerRadius(newCornerRadius: slider.value)
}

func updateViewCornerRadius(newCornerRadius : Float) {

    if border != nil {
        border?.removeFromSuperlayer()
    }

    let cornerRadius = CGFloat(newCornerRadius)

    testView.layer.cornerRadius = cornerRadius

    border = CAShapeLayer()
    border!.masksToBounds = true
    border!.cornerRadius = cornerRadius
    border!.strokeColor = UIColor.black.cgColor
    border!.lineDashPattern = [1, 0]
    border!.frame = testView.bounds
    border!.fillColor = UIColor.clear.cgColor
    border!.path = UIBezierPath(roundedRect: testView.bounds, byRoundingCorners: UIRectCorner.allCorners, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)).cgPath
    border!.lineWidth = 12
    testView.layer.addSublayer(border!)
}

Has anybody ever dealt with this issue? Is there a setting on the UIView or CAShapeLayer I could set to get rid of it?

  • Try this answer: https://stackoverflow.com/questions/27861383/swift-how-to-set-corner-radius-of-imageview , and if that doesnt help, try changing the corner radius in "clean" fractions, like 0.05, 0.1, or 1 and see if the artifacts crop up. – solenoid Sep 01 '17 at 01:41
  • None of the answers found in the link have worked. I've tried applying "testView.layer.masksToBounds = true", "testView.clipsToBounds = true", and "testView.layoutIfNeeded()". I also tried rounding the cornerRadius value to nearest whole numbers (and similar with nearest first decimal point) and that doesn't make a difference. Vertical line artifacts continue to appear. – user8545256 Sep 07 '17 at 19:38

0 Answers0