Swift 中使用 CGAffineTransform

級別: ★★☆☆☆
標籤:「iOS」「Swift」「CGAffineTransform」
做者: 大成小棧
審校: QiShare團隊php


iOS 中的二維平面變換通常使用CGAffineTransform,又稱爲仿射變換。下面咱們來介紹一下仿射變換的基本原理和基本用法。git

1. 變換矩陣形式

仿射變換矩陣用於旋轉,縮放,平移或傾斜在圖形上下文中繪製的對象。該類型提供用於建立,鏈接和應用仿射變換的功能。github

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矩陣表示:web

因爲第三列始終爲(0,0,1),所以數據結構僅包含前兩列的值。 從概念上講,仿射變換將表明圖形中每一個點(x,y)的行向量與此矩陣相乘,從而產生一個表明相應點(x',y')的向量:objective-c

給定3 x 3矩陣,可以使用如下方程式將一個座標系中的點(x,y)轉換爲另外一座標系中的結果點(x',y')。swift

矩陣由此「連接」兩個座標系-它指定一個座標系中的點如何映射到另外一個座標系。 請注意,一般不須要直接建立仿射變換。例如,若是隻想繪製縮放或旋轉的對象,則無需構造仿射變換。最直接的方法來操做你的「圖紙」-不管是經過移動,縮放或旋轉是調用函數,或分別作這些操做。一般,只有在之後要重用時才應建立仿射變換。微信

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地址app


瞭解更多iOS及相關新技術,請關注咱們的公衆號:ide

小編微信:可加並拉入《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的啓動流程
奇舞週刊

相關文章
相關標籤/搜索