Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a Diagonal Line in Swift

I was wondering if it is possible to draw a diagonal line by using UIViews? I have successfully made a straight line (vertical/horizontal) but I can not find a way to rotate the line.

Thank you for your help!

like image 567
alex1511 Avatar asked Sep 09 '15 16:09

alex1511


1 Answers

Here is a basic example of a view that contains a diagonal line view in Swift 2. When the view's bounds change, the diagonal is adapted by adjusting it's length and the rotation angle.

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))
    }

}

Putting that into a plain view controller for demonstration purposes

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)
    }

}

yields the result

simulator screenshot showing a view with a diagonal line

like image 181
hennes Avatar answered Nov 03 '22 12:11

hennes