在 UIImageView 中的图像后面插入 CAShapeLayer
Insert CAShapeLayer behind Image in UIImageView
正如标题所说。我有一个 UIImageView,我正在将 CAShapeLayers 插入到视图中。问题是我不知道如何将它们插入到 UIImageView 的图像后面。任何建议将不胜感激,谢谢。
您可以尝试重新排序一些层,但您可能会被 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)
祝你好运!
正如标题所说。我有一个 UIImageView,我正在将 CAShapeLayers 插入到视图中。问题是我不知道如何将它们插入到 UIImageView 的图像后面。任何建议将不胜感激,谢谢。
您可以尝试重新排序一些层,但您可能会被 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)
祝你好运!