Swift 中使用 CGAffineTransform

级别: ★★☆☆☆
标签:「iOS」「Swift」「CGAffineTransform」
作者: 大成小栈
审校: QiShare团队


iOS 中的二维平面变换一般使用CGAffineTransform,又称为仿射变换。下面我们来介绍一下仿射变换的基本原理和基本用法。

1. 变换矩阵形式

仿射变换矩阵用于旋转,缩放,平移或倾斜在图形上下文中绘制的对象。该类型提供用于创建,连接和应用仿射变换的功能。

public struct CGAffineTransform {
    public var a: CGFloat
    public var b: CGFloat
    public var c: CGFloat
    public var d: CGFloat
    public var tx: CGFloat
    public var ty: CGFloat

    public init()
    public init(a: CGFloat, b: CGFloat, c: CGFloat, d: CGFloat, tx: CGFloat, ty: CGFloat)
}

仿射变换由3 x 3矩阵表示:

由于第三列始终为(0,0,1),因此数据结构仅包含前两列的值。
从概念上讲,仿射变换将代表图形中每个点(x,y)的行向量与此矩阵相乘,从而产生一个代表相应点(x',y')的向量:

给定3 x 3矩阵,可使用以下方程式将一个坐标系中的点(x,y)转换为另一坐标系中的结果点(x',y')。

矩阵由此“链接”两个坐标系-它指定一个坐标系中的点如何映射到另一个坐标系。
请注意,通常不需要直接创建仿射变换。例如,如果只想绘制缩放或旋转的对象,则无需构造仿射变换。最直接的方法来操作你的“图纸”-无论是通过移动,缩放或旋转是调用函数,或分别做这些操作。通常,只有在以后要重用时才应创建仿射变换。

CGAffineTransform的(a,b,c,d,tx,ty)默认参数是[ 1 0 0 1 0 0 ],
这几个的参数的作用:
a: 对应sx就是视图宽放大或缩小的比例,初始值1,一倍大小。
b: 旋转会用到,初始值0。
c: 旋转会用到,初始值0。
d: 对应sy就是视图高放大或缩小的比例,初始值1,一倍大小。
tx: 视图x轴平移,初始值0,没有平移。
ty: 视图y轴平移,初始值0,没有平移。

2. iOS中的平面变换CGAffineTransform

import UIKit

class AffineTransfromView: UIView {

    var buttonTitleArr: NSMutableArray = NSMutableArray.init()
    var imgView: UIImageView?
    
    open var hostCon: UIViewController?
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        self.initViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initViews() {
        
        let size = self.frame.size
        self.buttonTitleArr.addObjects(from: ["平移", "旋转", "缩放", "旋转平移缩放", "验证标准矩阵", "平移之后再转换", "倒置", "矩阵相乘", "点矩阵转换", "size矩阵转换", "rect 矩阵转换", "复位"])
        for i in 0 ..< buttonTitleArr.count {
            
            let title: String = buttonTitleArr.object(at: i) as! String
            let button: UIButton = UIButton.init(type: UIButton.ButtonType.system)
            button.setTitle(title, for: UIControl.State.normal)
            button.frame = CGRect.init(x: (size.width / 3.0) * CGFloat(i%3), y: 50.0 * CGFloat(i/3), width: size.width / 3.0, height: 50.0)
            button.addTarget(self, action: #selector(buttonClicked(button:)), for: UIControl.Event.touchUpInside)
            button.layer.borderColor = UIColor.lightGray.cgColor
            button.layer.borderWidth = 0.5
            self.addSubview(button)
            button.tag = i
        }
        
        let backView: UIView = UIView.init(frame: CGRect.init(x: 0.0, y: 0.0, width: 150.0, height: 150.0))
        backView.backgroundColor = UIColor.cyan
        backView.center = self.center;
        self.addSubview(backView)
        
        self.imgView = UIImageView.init(frame: backView.bounds)
        self.imgView?.image = UIImage.init(named: "affinetransform.jpeg")
        self.imgView?.center = self.center
        self.addSubview(self.imgView!)
        
    }
    
    @objc func buttonClicked(button: UIButton) {
        
        switch button.tag {
        case 0:
            self.translation()
        case 1:
            self.rotation()
        case 2:
            self.scale()
        case 3:
            self.allTransform()
        case 4:
            self.isIdentity()
        case 5:
            self.rotationAfterTranslation()
        case 6:
            self.invert()
        case 7:
            self.matrixMultiplication()
        case 8:
            self.pointTransform()
        case 9:
            self.sizeTransform()
        case 10:
            self.rectTransform()
        case 11:
            self.reset()
        default:
            break;
        }
    }
    
    func showAlert(alertMsg: String) {
        
        let alertController = UIAlertController(title: nil, message: alertMsg, preferredStyle: UIAlertController.Style.alert)
        let cancelAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel, handler: nil)
        alertController.addAction(cancelAction)
        self.hostCon?.present(alertController, animated: true, completion: nil)
    }
    
    
    func reset() {
        
        UIView.animate(withDuration: 0.3) {
            self.imgView?.transform = CGAffineTransform.identity
        }
    }
    
    func animate(transform: CGAffineTransform) {
        UIView.animate(withDuration: 0.3) {
            self.imgView?.transform = transform
        }
    }
    
    func translation() {
        
        self.reset()
        let transform: CGAffineTransform = CGAffineTransform(translationX: 50, y: 50)
        self.animate(transform: transform)
    }
    
    func rotation() {
        
        self.reset()
        let transform: CGAffineTransform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 4.0))
        self.animate(transform: transform)
    }
    
    func scale() {
        
        self.reset()
        let transform: CGAffineTransform = CGAffineTransform(scaleX: 0.5, y: 0.5)
        self.animate(transform: transform)
    }
    
    func allTransform() {
        
        self.reset()
        let transform: CGAffineTransform = CGAffineTransform(a: 0.5, b: 0.3, c: 0.5, d: 1.5, tx: 25, ty: 25)
        self.animate(transform: transform)
    }
    
    func isIdentity() {
        
        let isIdentity = self.imgView?.transform.isIdentity
        let alertMsg: String = isIdentity == true ? "是标准矩阵" : "不是标准矩阵"
        self.showAlert(alertMsg: alertMsg)
    }
    
    func rotationAfterTranslation() {
        
        self.reset()
        var translation = CGAffineTransform(translationX: 40, y: 40)
        translation = translation.rotated(by: CGFloat(Double.pi / 4.0))
        self.animate(transform: translation)
        
    }
    
    func invert() {
        
        self.reset()
        let translation = CGAffineTransform(translationX: 50, y: 50)
        let translationInverted = translation.inverted()
        self.animate(transform: translationInverted)
    }
    
    func matrixMultiplication() {
        
        self.reset()
        let translation = CGAffineTransform(translationX: 40, y: 40)
        let rotation = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 4.0))
        let transform: CGAffineTransform = translation.concatenating(rotation)
        self.animate(transform: transform)
    }
    
    func pointTransform() {
        
        let point = CGPoint.init(x: 100, y: 100)
        let transform = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 20, ty: 10)
        let transformedPoint = point.applying(transform)
        
        let alertMsg = NSString.init(format: "之前:%@\n之后:%@", point.debugDescription, transformedPoint.debugDescription)
        self.showAlert(alertMsg: alertMsg as String)
    }
    
    func sizeTransform() {
        
        let size = CGSize.init(width: 200, height: 200)
        //let transform = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 20, ty: 10)
        let transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2.0))
        let transformedSize = size.applying(transform)
        
        let alertMsg = NSString.init(format: "之前:%@\n之后:%@", size.debugDescription, transformedSize.debugDescription)
        self.showAlert(alertMsg: alertMsg as String)
    }
    
    func rectTransform() {
        
        let rect = CGRect.init(x: 0, y: 0, width: 300, height: 300)
        let transform = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 20, ty: 10)
        let transformedRect = rect.applying(transform)
        
        let alertMsg = NSString.init(format: "之前:%@\n之后:%@", rect.debugDescription, transformedRect.debugDescription)
        self.showAlert(alertMsg: alertMsg as String)
    }
}
示例

源码Github地址


了解更多iOS及相关新技术,请关注我们的公众号:

小编微信:可加并拉入《QiShare技术交流群》。

关注我们的途径有:
QiShare(简书)
QiShare(掘金)
QiShare(知乎)
QiShare(GitHub)
QiShare(CocoaChina)
QiShare(StackOverflow)
QiShare(微信公众号)

推荐文章:
元旦福利!QiShare给大家发2020新年红包啦~
iOS 性能监控(一)—— CPU功耗监控
iOS 性能监控(二)—— 主线程卡顿监控
iOS 性能监控(三)—— 方法耗时监控
初识Flutter web
用SwiftUI给视图添加动画
用SwiftUI写一个简单页面
iOS App启动优化(三)—— 自己做一个工具监控App的启动耗时
iOS App启动优化(二)—— 使用“Time Profiler”工具监控App的启动耗时
iOS App启动优化(一)—— 了解App的启动流程
奇舞周刊

推荐阅读更多精彩内容