Skip to content

Instantly share code, notes, and snippets.

@acalism
Created February 7, 2018 12:54
Show Gist options
  • Save acalism/cd43453f0e3e2cc1ad9478338d04f163 to your computer and use it in GitHub Desktop.
Save acalism/cd43453f0e3e2cc1ad9478338d04f163 to your computer and use it in GitHub Desktop.
为 CoreGraphics 添加一些有用的扩展
extension UIOffset {
/// 转换为 CGPoint 形式
var point: CGPoint {
return CGPoint(x: horizontal, y: vertical)
}
}
extension CGPoint {
/// 转换为 UIOffset
var offset: UIOffset {
return UIOffset(horizontal: x, vertical: y)
}
func offset(by o: CGPoint) -> CGPoint {
return CGPoint(x: x + o.x, y: y + o.y)
}
func offset(by o: UIOffset) -> CGPoint {
return CGPoint(x: x + o.horizontal, y: y + o.vertical)
}
}
/// 假定CGRect本身已标准化(standardized)
extension CGRect {
var center: CGPoint {
get { return CGPoint(x: midX, y: midY) }
set { origin = CGPoint(x: newValue.x - width / 2, y: newValue.y - height / 2) }
}
var bottomLeft: CGPoint {
return CGPoint(x: origin.x, y: origin.y + size.height)
}
var topRight: CGPoint {
return CGPoint(x: origin.x + size.width, y: origin.y)
}
var bottomRight: CGPoint {
return CGPoint(x: maxX, y: maxY)
}
/// 内缩
///
/// - Parameter inset: 要内缩的各边距
/// - SeeAlso: 与 UIEdgeInsetsInsetRect(_:_:) 完成一样的功能
mutating func inset(_ d: UIEdgeInsets) {
origin.x += d.left
origin.y += d.top
size.width -= d.xInset
size.height -= d.yInset
}
/// 与 inset(_:) 功能相同
func inset(by d: UIEdgeInsets) -> CGRect {
return CGRect(x: origin.x + d.left, y: origin.y + d.top, width: size.width - d.xInset, height: size.height - d.yInset)
}
/// 求rect的镜像
///
/// - Parameter x: 对称轴坐标
mutating func mirror(x: CGFloat) {
origin.x = x + x - origin.x - width
}
/// 求rect的镜像
///
/// - Parameter y: 对称轴坐标
mutating func mirror(y: CGFloat) {
origin.y = y + y - origin.y - height
}
/// 以原点为基点作scale
///
/// - Parameter scale: 倍数
/// - Returns: zoom后的结果
func scaled(_ scale: CGFloat) -> CGRect {
return CGRect(x: minX * scale, y: minY * scale, width: width * scale, height: height * scale)
}
/// 中间能放置的最大的正方形
var centerSquareRect: CGRect {
let s = min(width, height)
let x = (width - s) / 2, y = (height - s) / 2
let ei = UIEdgeInsets(top: y, left: x, bottom: y, right: x)
return UIEdgeInsetsInsetRect(self, ei)
}
}
extension UIEdgeInsets {
/// total horizontal inset
var xInset: CGFloat {
return left + right
}
/// total vertical inset
var yInset: CGFloat {
return top + bottom
}
/// inset边框的左上角坐标,相对于被inset的rect
var topLeft: CGPoint {
return CGPoint(x: left, y: top)
}
/// 运算符重载:求反
///
/// - Parameter operand: 被求反的操作数
/// - Returns: 求反的结果
static prefix func - (operand: UIEdgeInsets) -> UIEdgeInsets {
return UIEdgeInsets(top: -operand.top, left: -operand.left, bottom: -operand.bottom, right: -operand.right)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment