Frame、Bounds和Center以及坐标系转换

  1. 设置frame相当于设置了viewsuperview坐标系中的大小和位置,严格来说是centerbounds的一种便捷设置
  2. bounds代表了当前view的坐标系(view的大小和view坐标系的起点,不要轻易修改boundsorigin)
  3. center表示在superview坐标系中的位置(设置center之前应该首先设置bounds)superview和当前view坐标系的连接关系是canter,基于这个事实,不同坐标系上的点可以进行相互转换
  4. 如果使用center来设置view的位置时,当该view的宽或高不是整数,该view边缘可能坐落在频幕的像素点之间,可能导致视图模糊,可以使用下面的代码来调整viewframe: v.frame = v.frame.integral
  5. 不同级别之间的view可能要进行包含范围的判断,可能需要用到坐标转换,UIView提供了下面四个方法进行坐标转换
open func convert(_ point: CGPoint, to view: UIView?) -> CGPoint
open func convert(_ point: CGPoint, from view: UIView?) -> CGPoint
open func convert(_ rect: CGRect, to view: UIView?) -> CGRect
open func convert(_ rect: CGRect, from view: UIView?) -> CGRect

上面的方法中的view参数如果传入nil默认是self.view.window,在viewDidLoad方法中self.view.windownil(viewwindow属性有无可以表示当前view是否在界面上, viewDidLoad界面还没有显示出来)

有了上面坐标系的概念,上面的方法可以理解为:
原坐标系to目标坐标系
目标坐标系from原坐标系
所以转换某个viewframe(superview坐标系中的位置)到指定的view一般使用view.superview调用to方法或者指定view调用frome方法

class ViewController: UIViewController {
    
    let v1 = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
    var v2 = UIView(frame: CGRect(x: 50, y: 50, width: 60, height: 60))
    var v3 = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    
    override func viewDidLoad() {
        super.viewDidLoad()
        v1.backgroundColor = UIColor.blue
        v2.backgroundColor = UIColor.gray
        v3.backgroundColor = UIColor.red
        view.addSubview(v1)
        view.addSubview(v2)
        v2.addSubview(v3)

    let point = v2.convert(v3.center, to: view)
    let point = view.convert(v3.center, from: v2)
    }

//下面这个方法便于理解和使用
let point = v1.convert(v3.center, from: v3.superview)

convert(_ point: CGPoint, to view: UIView?) -> CGPoint方法的调用者是该点所在viewsupviewto后面传入需要转换到的视图,convert(_ point: CGPoint, from view: UIView?) -> CGPoint正好相反

UIView有一个方法func point(inside point: CGPoint, with event: UIEvent?) -> Bool可以判断点是否在view

你可能感兴趣的:(Frame、Bounds和Center以及坐标系转换)