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

相关推荐
点金石游戏出海4 小时前
每周资讯 | Krafton斥资750亿日元收购日本动画公司ADK;《崩坏:星穹铁道》新版本首日登顶iOS畅销榜
游戏·ios·业界资讯·apple·崩坏星穹铁道
90后的晨仔6 小时前
Xcode16报错: SDK does not contain 'libarclite' at the path '/Applicati
ios
finger244807 小时前
谈一谈iOS线程管理
ios·objective-c
Digitally7 小时前
如何将大型视频文件从 iPhone 传输到 PC
ios·iphone
梅名智8 小时前
IOS 蓝牙连接
macos·ios·cocoa
美狐美颜sdk15 小时前
跨平台直播美颜SDK集成实录:Android/iOS如何适配贴纸功能
android·人工智能·ios·架构·音视频·美颜sdk·第三方美颜sdk
恋猫de小郭20 小时前
Meta 宣布加入 Kotlin 基金会,将为 Kotlin 和 Android 生态提供全新支持
android·开发语言·ios·kotlin
泓博20 小时前
Objective-c把字符解析成字典
开发语言·ios·objective-c
Daniel_Coder21 小时前
Xcode 中常用图片格式详解
ios·xcode·swift
瓜子三百克21 小时前
Objective-C 路由表原理详解
开发语言·ios·objective-c