Сначала я подумал, что вы не можете установить образ в содержимое CAShapeLayer и заставить его работать, но я ошибся.Это работает.Рассмотрим этот код:
class ImageWithShapeView: UIView {
let shapeLayer = CAShapeLayer()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.borderWidth = 1.0
shapeLayer.frame = self.bounds
//Load an image into the shape layer's contents property.
if let image = UIImage(named: "WareToLogo") {
shapeLayer.contents = image.cgImage
layer.addSublayer(shapeLayer)
}
let path = UIBezierPath()
shapeLayer.lineWidth = 2.0
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
let radius = (bounds.midX + bounds.midY) / 4.0
path.addArc(withCenter: CGPoint(x: bounds.midX, y: bounds.midY), radius: radius, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true)
path.move(to: CGPoint(x:0, y:0))
path.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
path.move(to: CGPoint(x: bounds.width, y: 0))
path.addLine(to: CGPoint(x: 0, y: bounds.height))
shapeLayer.path = path.cgPath
}
}
Это работает и создает следующее, когда я добавляю ImageWithShapeView
в свой проект.(Я использую раскадровку, поэтому я реализовал UIView.init(coder:)
. Если вы создаете свои представления в коде, возможно, вы захотите вместо этого реализовать UIView.init(frame:)
)
![enter image description here](https://i.stack.imgur.com/RyXj1.png)