在Swift中绘制对角线

ale*_*511 4 cocoa-touch ios autolayout swift

我想知道是否可以使用UIViews绘制对角线?我已经成功地做了一条直线(垂直/水平),但我找不到旋转线的方法.

谢谢您的帮助!

hen*_*nes 6

以下是包含Swift 2中对角线视图的视图的基本示例.当视图边界发生变化时,通过调整对角线的长度和旋转角度来调整对角线.

import UIKit
import Foundation

class ViewWithDiagonalLine: UIView {

    private let line: UIView

    private var lengthConstraint: NSLayoutConstraint!

    init() {
        // Initialize line view
        line = UIView()
        line.translatesAutoresizingMaskIntoConstraints = false
        line.backgroundColor = UIColor.redColor()

        super.init(frame: CGRectZero)

        clipsToBounds = true // Cut off everything outside the view

        // Add and layout the line view

        addSubview(line)

        // Define line width
        line.addConstraint(NSLayoutConstraint(item: line, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 10))

        // Set up line length constraint
        lengthConstraint = NSLayoutConstraint(item: line, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 0)
        addConstraint(lengthConstraint)

        // Center line in view
        addConstraint(NSLayoutConstraint(item: line, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: line, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // Update length constraint and rotation angle
        lengthConstraint.constant = sqrt(pow(frame.size.width, 2) + pow(frame.size.height, 2))
        line.transform = CGAffineTransformMakeRotation(atan2(frame.size.height, frame.size.width))
    }

}
Run Code Online (Sandbox Code Playgroud)

将其放入普通视图控制器以进行演示

class ViewController: UIViewController {

    override func viewDidLoad() {
        let v = ViewWithDiagonalLine()
        v.frame = CGRectMake(100, 100, 100, 200)
        v.layer.borderColor = UIColor.blueColor().CGColor
        v.layer.borderWidth = 1
        view.addSubview(v)
    }

}
Run Code Online (Sandbox Code Playgroud)

产生结果

模拟器截图显示对角线的视图

  • @alex1511 只需将角度计算更改为`CGFloat(M_PI) - atan2(frame.size.height, frame.size.width)`。 (2认同)