如果有人在寻找Swift 3 或 4 工作解决方案:
let imageSize: CGFloat = 64.0
// Create a container which has a shadow
let imageCotainer = UIView(frame: CGRect(x: 0, y: 0, width: imageSize, height: imageSize))
imageCotainer.clipsToBounds = false
imageCotainer.layer.shadowColor = UIColor.black.cgColor
imageCotainer.layer.shadowOpacity = 0.2
imageCotainer.layer.shadowOffset = CGSize(width: 0, height: 1)
imageCotainer.layer.shadowRadius = 2
// Create an image view that will be inserted into the container view
let imageView = UIImageView(frame: imageCotainer.bounds)
imageView.image = yourImage
imageView.clipsToBounds = true
let cornerRadius = imageView.frame.height / 2
imageView.layer.cornerRadius = cornerRadius
// Draw a shadow
imageCotainer.layer.shadowPath = UIBezierPath(roundedRect: imageCotainer.bounds, cornerRadius: cornerRadius).cgPath
// Add image into container
imageCotainer.addSubview(imageView)
有时您还需要为容器内的图像设置约束,但在某些情况下它也可以在没有它的情况下工作。但如果不是,请添加以下内容:
// Set constraints for the image inside the container view
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.topAnchor.constraint(equalTo: imageCotainer.topAnchor).isActive = true
imageView.leftAnchor.constraint(equalTo: imageCotainer.leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: imageCotainer.rightAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: imageCotainer.bottomAnchor).isActive = true
imageView.heightAnchor.constraint(equalToConstant: imageSize).isActive = true
imageView.widthAnchor.constraint(equalToConstant: imageSize).isActive = true