iOS_convert point or rect 坐标和布局转换+判断

文章目录

    • [1. 坐标转换](#1. 坐标转换)
    • [2. 布局转换](#2. 布局转换)
    • [3. 包含、相交](#3. 包含、相交)

如:有3个色块

swift 复制代码
let view1 = UIView(frame: CGRect(x: 100.0, y: 100.0, width: 300.0, height: 300.0))
view1.backgroundColor = UIColor.cyan
self.view.addSubview(view1)

let view2 = UIView(frame: CGRect(x: 50.0, y: 50.0, width: 100.0, height: 100.0))
view2.backgroundColor = .red
view1.addSubview(view2)

let view3 = UIView(frame: CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0))
view3.backgroundColor = .blue
view1.addSubview(view3)

1. 坐标转换

from: 从哪个坐标系 to: 到哪个坐标系

swift 复制代码
/// view1 上的 view2 在 self.view 上的位置
print("view2.center on self.view: \(view1.convert(view2.center, to: self.view))")
/// 同上
print("view2.center on self.view: \(self.view.convert(view2.center, from: view1))")

// print
// view2.center: (100.0, 100.0)
// view2.center on self.view: (200.0, 200.0)
// view2.center on self.view: (200.0, 200.0)

2. 布局转换

swift 复制代码
/// view1 上的 view2 在 self.view 上的位置
print("view2 on self.view: \(view1.convert(view2.frame, to: self.view))")
/// 同上
print("view2 on self.view: \(self.view.convert(view2.frame, from: view1))")

// print
// view2 on self.view: (150.0, 150.0, 100.0, 100.0)
// view2 on self.view: (150.0, 150.0, 100.0, 100.0)

3. 包含、相交

swift 复制代码
/// view1 是否包含 view2.center
print("view1 contains view2.center: \(CGRectContainsPoint(view1.frame, view2.center))")
/// view1 是否包含 view2
print("view1 contains view2: \(CGRectContainsRect(view1.frame, view2.frame))")
/// view2 和 view3 是否相交
print("view2 intersect view3: \(CGRectIntersectsRect(view2.frame, view3.frame))")

// print
// view1 contains view2.center: true
// view1 contains view2: false
// view2 intersect view3: true

github Demo

相关推荐
Swift社区5 小时前
iOS 基于 Foundation Model 构建媒体流
ios·iphone·swift·媒体
库奇噜啦呼7 小时前
【iOS】音频与视频播放
ios·音视频·cocoa
大熊猫侯佩15 小时前
黑衣人档案:用 Apple Foundation Models + SwiftUI 打造 AI 聊天机器人全攻略
ios·swiftui·ai编程
大熊猫侯佩15 小时前
侠客行・iOS 26 Liquid Glass TabBar 破阵记
ios·swiftui·swift
2501_9160074717 小时前
手机使用过的痕迹能查到吗?完整查询指南与步骤
android·ios·智能手机·小程序·uni-app·iphone·webview
從南走到北18 小时前
JAVA国际版同城外卖跑腿团购到店跑腿多合一APP系统源码支持Android+IOS+H5
android·java·ios·微信小程序·小程序
alengan20 小时前
苹果企业签名流程
ios·iphone
Digitally1 天前
如何在Mac上同步iPhone短信
macos·ios·iphone
2501_915106321 天前
App HTTPS 抓包 工程化排查与工具组合实战
网络协议·ios·小程序·https·uni-app·php·iphone
2501_916008891 天前
金融类 App 加密加固方法,多工具组合的工程化实践(金融级别/IPA 加固/无源码落地/Ipa Guard + 流水线)
android·ios·金融·小程序·uni-app·iphone·webview