我想知道是否可以使用UIViews绘制对角线?我已经成功地做了一条直线(垂直/水平),但我找不到旋转线的方法。
感谢您的帮助!
答案 0 :(得分: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))
}
}
将其放入普通视图控制器以进行演示
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)
}
}
产生结果
答案 1 :(得分:0)
您可以通过设置UIView
属性来轮换transform
。您希望使用CGAffineTransformMakeRotation
或CGAffineTransformRotate
。
但是,您最好使用CAShapeLayer
并将其path
属性设置为您想要绘制的行。