gpt4 book ai didi

ios - 将图像添加到 CAShapeLayer

转载 作者:行者123 更新时间:2023-11-30 11:07:37 26 4
gpt4 key购买 nike

我正在尝试在嵌套在 UIView 层中的 CAShapeLayer 内渲染静态图像。形状的所有装饰(即边框、颜色、路径等)都会在 View 中正确渲染。

但是,为CALayer.contents属性提供的CGImage在任何时候都不会在 View 中呈现(据我所知告诉)。我已经尝试弄清楚这种行为有一段时间了,但对 Apple 的文档感到困惑:

If you are using the layer to display a static image, you can set this property to the CGImage containing the image you want to display.... Assigning a value to this property causes the layer to use your image rather than create a separate backing store.

If the layer object is tied to a view object, you should avoid setting the contents of this property directly. The interplay between views and layers usually results in the view replacing the contents of this property during a subsequent update.

很高兴知道!这可能正是这种情况下发生的情况:UIView 正在更新并替换其内容。除了提供的解决方法不是很清楚,而且我无法找到解决此问题的示例。

有人对如何在 CAShapeLayer 上“间接”设置静态图像并避免其被 super View 删除(几乎立即)有任何建议吗?

最佳答案

起初我以为你无法将图像安装到 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 时创建以下内容到我的项目。 (我使用的是 Storyboard,所以我实现了 UIView.init(coder:) 。如果您在代码中创建 View ,您可能需要实现 UIView.init(frame:) )

enter image description here

关于ios - 将图像添加到 CAShapeLayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52527420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com