您可以尝试进行一些层重新排序,但UIImageView自己的内部代码可能会阻碍您。我的建议是创建一个容器视图,并在其中添加子层,然后将图像视图添加为子视图(这实际上也是将其添加为子层)。只要图像具有透明度并且UIImageView不是不透明的,它就会工作。
这个代码在操场上对我有效:
let container = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let imageView = UIImageView(frame: container.bounds)
imageView.image = UIImage(named: "duck.png")
imageView.isOpaque = false
let shape = CAShapeLayer()
shape.path = UIBezierPath(roundedRect: container.bounds, cornerRadius: 2).cgPath
shape.strokeColor = UIColor.black.cgColor
shape.lineWidth = 10
shape.fillColor = UIColor.blue.cgColor
shape.borderColor = UIColor.black.cgColor
container.layer.addSublayer(shape)
container.addSubview(imageView)
祝你好运