从两侧在UIView上绘制对角线

时间:2018-02-22 09:59:22

标签: ios iphone swift swift4

Window grill

从窗口烧烤两侧创建对角线。

如何以编程方式设计窗格(swift4)?

我在下面给出了错误的逻辑,它绘制了一条横过视图的一侧诊断线。

        let height = view.frame.size.height
    let width  = view.frame.size.width
   let  space = 10
    for i in stride(from: 0, through: 2*Int(width), by: space) {
        view.layer.addSublayer(DesignShape.addLine(fromPoint: CGPoint(x:
            i, y: 0), toPoint: CGPoint(x:CGFloat(i-Int(width)), y: height), color: UIColor.black,lineWidth :2))
    }

DesignShape.addLine 是使用 UIBezierPaths 在两个点之间绘制线条的方法。

1 个答案:

答案 0 :(得分:1)

我已尝试使用UIBezierPath进行设计。这可能会对您的问题有所了解。

<强>编码

@IBOutlet weak var shapeView: UIView!
// CONSTRAINTS top 20, left and right 16, height as 320

override func viewDidAppear(_ animated: Bool) {
   howManyGrillWeNeed(grillCount : 17, grillWidth: 40, grillHeight : 60)
}

func howManyGrillWeNeed(grillCount: Int, grillWidth: CGFloat, grillHeight: CGFloat)
{
    let xPositionDiff = Int((shapeView.frame.width / grillWidth))
    var xPosiitonCount : Int = 0
    var yPosiitonCount : Int = -1

    for i in 0..<grillCount
    {
        if i % xPositionDiff == 0
        {
            xPosiitonCount = 0
            yPosiitonCount = yPosiitonCount + 1
            print("newxLine")
        }
        else
        {
            xPosiitonCount = xPosiitonCount + 1
        }
        let grillVw = UIView(frame: CGRect(x: 0, y: 0, width: grillWidth, height: grillHeight))
        grillVw.backgroundColor = UIColor.white


        grillVw.frame.origin.x = CGFloat(xPosiitonCount) * grillWidth
        grillVw.frame.origin.y = CGFloat(yPosiitonCount) * grillHeight

        let layerWidth = grillWidth
        let layerHeight = grillHeight
        let bezierPath = UIBezierPath()
        bezierPath.move(to: CGPoint(x: 0, y: layerHeight / 2))

        bezierPath.addLine(to: CGPoint(x: layerWidth / 2, y: 0))
        bezierPath.addLine(to: CGPoint(x: layerWidth, y: layerHeight / 2))
        bezierPath.addLine(to: CGPoint(x: layerWidth / 2, y: layerHeight))
        bezierPath.addLine(to: CGPoint(x: 0, y: layerHeight / 2))


        // Mask to Path
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = bezierPath.cgPath
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.fillColor = UIColor.orange.cgColor
        shapeLayer.lineWidth = 1.0

        grillVw.layer.addSublayer(shapeLayer)
        //grillVw.layer.mask = shapeLayer

        shapeView.addSubview(grillVw)
    }
}

<强>输出

enter image description here