微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift-如何使用CAShapeLayer绘制3颗类似棒球场的钻石?

如何解决Swift-如何使用CAShapeLayer绘制3颗类似棒球场的钻石?

我有一个视图控制器。在内部,我有一个视图(A),在这个视图(A)中,我想用CAShapeLayer像棒球场一样绘制3颗钻石。您可以在下面看到我要绘制的示例。

enter image description here

但是我不知道该怎么做?你能帮我吗?

最诚挚的问候

解决方法

应使用嵌套UIStackViewCATransform3DMakeRotation轻松创建。

https://github.com/sauvikapple/StackOverflowAns4229726处检查我的代码。

enter image description here

,

设置您的容器视图和棒球钻石视图:

let dummyWiew: UIView = {
    let v = UIView()
    v.backgroundColor = .gray
    v.translatesAutoresizingMaskIntoConstraints = false
    
    return v
}()

let dummyWiew2: UIView = {
    let v = UIView()
    v.backgroundColor = .yellow
    v.translatesAutoresizingMaskIntoConstraints = false
    
    return v
}()

let dummyWiew3: UIView = {
    let v = UIView()
    v.backgroundColor = .gray
    v.translatesAutoresizingMaskIntoConstraints = false
    
    return v
}()

let containerView: UIView = {
    let v = UIView()
    v.backgroundColor = .clear
    v.translatesAutoresizingMaskIntoConstraints = false
    
    return v
}()

在viewDidLoad中设置容器视角旋转之后,创建stacView并添加约束:

view.backgroundColor = UIColor(white: 1,alpha: 0.1)
    
    let angleInRadians = -135 / 180.0 * CGFloat.pi
    let rotation = containerView.transform.rotated(by: angleInRadians)
    containerView.transform = rotation
    
    view.addSubview(containerView)
    containerView.heightAnchor.constraint(equalToConstant: 180).isActive = true
    containerView.widthAnchor.constraint(equalToConstant: 180).isActive = true
    containerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    containerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    
    let stackView = UIStackView(arrangedSubviews: [dummyWiew,dummyWiew2])
    stackView.distribution = .fillEqually
    stackView.spacing = 20
    stackView.translatesAutoresizingMaskIntoConstraints = false
    
    containerView.addSubview(stackView)
    stackView.heightAnchor.constraint(equalToConstant: 80).isActive = true
    stackView.widthAnchor.constraint(equalToConstant: 180).isActive = true
    stackView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
    stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    
    containerView.addSubview(dummyWiew3)
    dummyWiew3.bottomAnchor.constraint(equalTo: stackView.topAnchor,constant: -20).isActive = true
    dummyWiew3.trailingAnchor.constraint(equalTo: stackView.trailingAnchor,constant: 0).isActive = true
    dummyWiew3.leadingAnchor.constraint(equalTo: dummyWiew2.leadingAnchor).isActive = true
    dummyWiew3.heightAnchor.constraint(equalToConstant: 80).isActive = true

这是结果

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。