Edward Edward - 1 month ago 16
Swift Question

Strange border glitch of an ImageView

I made a custom view containing some imageviews. But they have a strange border glitch: there is an offset from the edge of the image revealing some background colour.

enter image description here

This is how I make image views:

for (index, image) in self.images.enumerated()
{
if index == maxIndex {
break
}

let imageView = UIImageView(frame: CGRect(x: offsetX, y: 0, width: self.height, height: self.height))
imageView.cornerRadius = self.height / 2
imageView.contentMode = .scaleAspectFill
imageView.image = image
imageView.layer.borderColor = AppColors.background?.cgColor
imageView.layer.borderWidth = 2
self.addSubview(imageView)
self.imageViews.append(imageView)

offsetX += self.height / 2 + 5
}


There are no views under imageviews. Subviews count is 4

Answer

That's a aliasing issue. Some edge pixels of border are semi-transparent and because of that you can see the underlaying content.

You can try adding a custom CAShapeLayer with circle path:

let border = CAShapeLayer()
border.frame = imageView.bounds
border.lineWidth = 4 //doubled width
border.path = UIBezierPath(ovalIn: border.bounds).cgPath
border.strokeColor = UIColor.white.cgColor
border.fillColor = UIColor.clear.cgColor
imageView.layer.addSublayer(border)