swift 的CGRect + Geometry.swift

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 的CGRect + Geometry.swift相关的知识,希望对你有一定的参考价值。

//
//  CGRect+Geometry.swift
//
//  Created by Artem Krachulov.
//  Copyright (c) 2016 Artem Krachulov. All rights reserved.
//	http://www.artemkrachulov.com
//

import UIKit

extension CGRect {
  
  /// The center of rectangle (ignoring origin property) and is measured in points. Setting this property changes the values of the rectangle accordingly.
  ///
  /// Usage:
  ///
  ///     let rect1 = CGRectMake(0, 0, 500, 400)
  ///     let rect1Center = rect1.center // {x 250 y 200}
  ///
  ///     var rect2 = CGRectMake(0, 0, 200, 350)
  ///
  ///     rect2.center = rect1Center // {x 150 y 25 w 200 h 350}
  ///
  public var center: CGPoint {
    get {
      return CGPointMake(width / 2, height / 2)
    }
    set(newValue) {
      origin = CGPointMake(newValue.x - width / 2, newValue.y - height / 2)
    }
  }
  
  /// Returns scaled and centered rectangle to fit size target rectangle.
  ///
  /// Usage:
  ///
  ///     let rect1 = CGRectMake(0, 0, 500, 400)
  ///     var rect2 = CGRectMake(0, 0, 200, 350)
  ///
  ///     let fitScaleRect = rect1.fitScaleRelativeTo(rect2) // {x 0 y 95 w 200 h 160}
  ///
  public func fitScaleRelativeTo(rect: CGRect) -> CGRect {
    
    var newRect = self
    newRect.size = newRect.size.increaseBy(multiplier: CGSizeGetFitScaleMultiplier(size, relativeToSize: rect.size))
    newRect.center = rect.center
    
    return newRect
  }
  
  /// Returns scaled and centered rectangle to fill size target rectangle.
  ///
  /// Usage:
  ///
  ///     let rect1 = CGRectMake(0, 0, 500, 400)
  ///     var rect2 = CGRectMake(0, 0, 200, 350)
  ///
  ///     let fillScaleRect = rect1.fillScaleRelativeTo(rect2) // {x -118.75 y 0 w 437.5 h 350}
  ///
  public func fillScaleRelativeTo(rect: CGRect) -> CGRect {
    
    var newRect = self
    newRect.size = newRect.size.increaseBy(multiplier: CGSizeGetFillScaleMultiplier(size, relativeToSize: rect.size))
    newRect.center = rect.center
    
    return newRect
  }
  
  /// Return rectangle where frame increased by multiplier.
  ///
  /// Original method
  ///
  ///     func increaseBy(multiplier multiplier: CGFloat) -> CGSize
  public func increase(byMultiplier multiplier: CGFloat) -> CGRect {
    return CGRectMake(origin.x*multiplier, origin.y*multiplier, size.width*multiplier, size.height*multiplier)
  }
}

以上是关于swift 的CGRect + Geometry.swift的主要内容,如果未能解决你的问题,请参考以下文章

Swift:字典键为 CGRect

Swift:使用 CGRect 设置 UIButton 图像

swift CGSize + Geometry.swift

反转 CGRect - Swift

来自 Swift 的 CGRect 和 CGSize 扩展在 Objective-C 中不可见

来自 Swift 的 CGRect 和 CGSize 扩展在 Objective-C 中不可见