4

When i add a border to a UIImageView, i get little black strips on the following picture. I try my app on a real iPhone and i can see the little strips too. How can i remove this or where is the issue of this?

Anyone have an idea?

enter image description here

Here is my code for the UIImageView:

//Setup ProfileImageView
    profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2
    profileImageView.clipsToBounds = true
    profileImageView.layer.borderColor = UIColor.white.cgColor
    profileImageView.layer.borderWidth = 4.0
    profileImageView.layer.shadowOpacity = 0.12
    profileImageView.layer.shadowOffset = CGSize(width: 0, height: 2)
    profileImageView.layer.shadowRadius = 2
    profileImageView.layer.shadowColor = UIColor.black.cgColor

And my Storyboard Settings:

enter image description here

I use the Xcode 10 beta 6... Could that be a problem?

Niklas
  • 1,638
  • 4
  • 19
  • 48

1 Answers1

1

It looks like the image is bleeding out of the layer's borders when you set the cornerRadius. See this post: iOS: Rounded rectangle with border bleeds color

The CAShapeLayer solution that was suggested by @FelixLam in the aforementioned post could be something like this:

let lineWidth: CGFloat = 4.0 // the width of the white border that you want to set
let imageWidth = self.profileImageView.bounds.width
let imageHeight = self.profileImageView.bounds.height

// make sure width and height are same before drawing a circle
if (imageWidth == imageHeight) {
    let side = imageWidth - lineWidth
    let circularPath = UIBezierPath.init(ovalIn: CGRect(lineWidth / 2, lineWidth / 2, side, side))

    // add a new layer for the white border
    let borderLayer = CAShapeLayer()
    borderLayer.path = circularPath.CGPath
    borderLayer.lineWidth = lineWidth
    borderLayer.strokeColor = UIColor.white.cgColor
    borderLayer.fillColor = UIColor.clear.cgColor
    self.profileImageView.layer.insertSublayer(borderLayer, at: 0)

    // set the circle mask to your profile image view
    let circularMask = CAShapeLayer()
    circularMask.path = circularPath.CGPath
    self.profileImageView.layer.mask = circularMask
}
Pranay
  • 846
  • 6
  • 10
  • thanks for your answer. When i add this code to my project, i get the following error in this line: "let side = imageWidth - lineWidth": Binary operator '-' cannot be applied to operands of type 'CGFloat' and 'Double' How can i solve the compiler issue? – Niklas Sep 01 '18 at 11:46
  • It’s probably because of the first line. By default the `lineWidth` is going to be declared as Double. Fix it by changing to `let lineWidth: CGFloat = 4.0`. Anyway, I’ll update my answer as well – Pranay Sep 02 '18 at 14:34