【发布时间】:2015-09-09 16:10:41
【问题描述】:
我想知道是否可以使用 UIViews 绘制对角线?我已经成功地画了一条直线(垂直/水平),但我找不到旋转直线的方法。
感谢您的帮助!
【问题讨论】:
标签: ios swift cocoa-touch autolayout
我想知道是否可以使用 UIViews 绘制对角线?我已经成功地画了一条直线(垂直/水平),但我找不到旋转直线的方法。
感谢您的帮助!
【问题讨论】:
标签: ios swift cocoa-touch autolayout
这是一个在 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)
}
}
产生结果
【讨论】:
CGFloat(M_PI) - atan2(frame.size.height, frame.size.width)即可。
您可以通过设置transform 属性来旋转UIView。你会想使用CGAffineTransformMakeRotation 或CGAffineTransformRotate。
但是,您最好使用CAShapeLayer 并将其path 属性设置为您要绘制的线。
【讨论】: