gpt4 book ai didi

ios - 在 UIView 容器中添加 bezierpath

转载 作者:行者123 更新时间:2023-11-30 12:47:19 25 4
gpt4 key购买 nike

我试图在 UIView 容器内(底部)添加贝塞尔路径(三角形),但是我似乎无法正确理解 UIView 容器的要点。我得到这个结果(其中似乎有一条三角形显示在容器 View 的左侧):enter image description here

我想要一个输出,例如:

enter image description here

这是我迄今为止的代码:

   // adding container to add image
self.topContainer.backgroundColor = UIColor(red: 49/255, green: 207/255, blue: 203/255, alpha: 1)
// self.topContainer.backgroundColor = UIColor.white
self.topContainer.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(self.topContainer)


self.topContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
self.topContainer.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.55).isActive = true
self.topContainer.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true

let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: self.topContainer.frame.size.height))
bezierPath.addLine(to: CGPoint(x: self.topContainer.frame.size.width, y: 222))
bezierPath.addLine(to: CGPoint(x: self.topContainer.frame.size.width, y: self.topContainer.frame.size.height))
bezierPath.addLine(to: CGPoint(x: 0, y: self.topContainer.frame.size.height))

UIColor.white.setFill()
bezierPath.fill()
bezierPath.lineWidth = 1
bezierPath.close()

let shapeLayer = CAShapeLayer()
shapeLayer.path = bezierPath.cgPath
shapeLayer.lineWidth = 2.0
shapeLayer.strokeColor = UIColor.white.cgColor
shapeLayer.fillColor = UIColor.white.cgColor
self.topContainer.layer.addSublayer(shapeLayer)

最佳答案

您显然是在 View Controller 的 viewDidLoad 中执行此代码。你应该:

  • 删除 UIColor.white.setFill()path.fill() 代码。仅当在图形上下文中绘制时才有意义(例如 UIViewdraw 方法或在 UIGraphicsBegin/EndImageContext 中)。只需构造 CAShapeLayer 并将其添加到 View /图层层次结构中,操作系统就会为您绘制/填充它。

  • 继续在 viewDidLoad 中创建并配置 CAShapeLayer,但移动 UIBezierPath 的创建以及CAShapeLayer 到 View Controller viewDidLayoutSubviews路径方法。 View 的框架在 viewDidLoad 期间通常是未知的,并且肯定容易被更改(通过约束或自动调整大小蒙版)。调用 viewDidLayoutSubviews 时,frame 已正确配置(如果主视图的 frame 发生更改,将再次调用)。

关于ios - 在 UIView 容器中添加 bezierpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41475832/

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